Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    PHP


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Conditional Statements And Loops


Not long ago I was asked to give PHP lections to some private IT
school. I'm on second lection now, and will be teaching my :) students
conditional statements (if..else and switch) and loops (while and for).
That was my story, now the question.

Can you give me an advise on some geeky use of those statements to stir
up some enthusiasm in students.




View Complete Forum Thread with Replies

Related Forum Messages:
Question On Conditional Statements
I'm a perl programmer and am trying to learn PHP.

So far I have figured out most of the differences, but have not been able to
find out how to do the following:

When running through a loop, how can you test two separate conditions
against the same $element of an array. For example, this is how I thought it
would be done (similar to Perl), but it did not work:

if (eregi("apple", $line) and (eregi("orange", $line) {

do whatever;

}

Basically testing each line of an array to see if both the words "apple" and
"orange" are present.

Also, is there any equivalent to the following from Perl while running
through a loop:

next if (whatever conditions);
last if (whatever conditions);

View Replies !
Avoiding Endless Conditional Statements
Here is my problem. I want to make a webapp that will basically take
the work out of finding what tool works for what situation. There are
5 factors that go into tool selection. 1)Material Group, 2)Insert
Radius, 3)Insert Type and Size, and 2 others that I can't remember
off-hand. There are probably about 1000 different scenarios that I
have to code for..(there are several blank table cells and it's not
setup as you might imagine, there is a lot of overlapping), and I
desperately want to avoid making a gigantic conditional statement. I'm
afraid that I really have to provide a picture of what I'm doing here,
so I will do that. Here is the link.
You only see 3 of the 5
factors on this page, and the other 2 have to do with whether this
table or one of many other tables (not pictured) will be used.

So, now that I've confused everyone. That's my table. What's a good
way to go about programming that sucker in so that people don't have to
do all the "work" involved to figure out what tools they need. They
should just be able to choose selections from 5 dropdown boxes and get
one tool back. A tool is something like "10.655.600".

View Replies !
Mysql Real Escape String() In Conditional Statements
I created the following bit of code that allows me to pass a MySQL conditional statement to a function.

I am trying to figure out where and how would I go about incorporating the mysql_real_escape_string() function?

Is there a way to call the mysql_real_escape_string() in the function itself? Code:

View Replies !
Possible To Include Conditional IF Statements Inside Switch Case Declarations?
Is it possible to include conditional IF statements inside switch case declarations?

For example... Instead of doing...

View Replies !
Nesting Result Loops Within Result Loops Possible?
I'm looping through a query, and inside the while result output, I am trying to loop through a second query (created from the 1st query's row results).

I have checked that both queries return info.

I can see that the 1st while result output works fine, but when I get to the inner while result output, it never returns any rows (nothing in the while loop evaluates).

So, IS it possible to nest one query's output loop within another, or am I doing something wrong?

View Replies !
For Loops Vs While Loops
Seems like every day I read 2-3 posts espousing the use of Foreach over While and vice versa.

Time to set the record straight...

http://www.php.lt/benchmark/phpbench.php (not my page, but it was far easier than coding it myself)

And the winner is... For loops.

There you have it. Concrete proof, instead of conjecture. For loops are faster. I guess I'll have to code up some tests to see if it's faster to grab the count from a mysql query and use a for loop vs using a while loop to iterate over a returned record set.

Feel free to comment, but please, cite refrences if you wish to contradict what I have written. I'm tired of hearing "facts" that are unsubstantiated.

View Replies !
Using While Loops
Does anyone know how collect user information from a database for each user, perform an operation on it, then output each user's information as a seperate variable?

I have it to the point where I set up a while loop that retrieves each user's information but I can't automate the setting of the unique variables.

View Replies !
Using 2 Loops With MAX()/MIN()
I am developing a simple messageboard that will list threads. There will be the first post of the thread and directly underneath will be the last reply to that thread. My problem is that instead of the last reply, the last post in the db is being displayed under all of the threads.

actionID is the auto incremented primary key. subjectID is an integer that is the same for a post and all of its replies. A new post will have the next incremented integer. Code:

View Replies !
Using Loops
i tried using one for trying to display how many pages of message you have in your inbox.. (this froze my computer)

heres some of my code
echo "<form METHOD=get><input type=hidden name=view value=Message><table width=70% border=0 cellspacing=1 cellpadding=0>
<tr><td background=images/forum_board.jpg height=25 width=0></td><td background=images/forum_board.jpg height=25 width=33%><b><center>Subject</center></b></td><td background=images/forum_board.jpg height=25 width=33%><b><center>From</center></b></td><td background=images/forum_board.jpg height=25 width=33%><b><center>Date</center></td></tr>";
$slimit = $action*15;
$llimit = ($action+1)*15;
$pms = mysql_query("SELECT * FROM pm WHERE pm_to='$get_user[id]' ORDER BY id DESC LIMIT $slimit, $llimit");..............

View Replies !
While Loops
I have to put a while loop in an assignment and I was wondering if someone could explain what it does and possibly give me an example then I can at least attempt it on my own.

View Replies !
IF Loops Help
I read a little tutorial how to start with if loops and now I am stuck with this one: Quote:

if(isset($_POST['Submit'])){

//Shortening Variables
$userid = $_POST['userid'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$vpassword = $_POST['vpassword'];
$ad1 = $_POST['ad1'];
$ad2 = $_POST['ad2'];
$zipcode = $_POST['zipcode'];
$hphone = $_POST['hphone'];
$mphone = $_POST['mphone'];
$pemail = $_POST['pemail'];
...................

View Replies !
Conditional
I am having an issue here that no matter what happens, my else statement is always displayed with my if! Can someone help me, I can't seem to find where I messed up. PHP Code:

if ($_GET['cat'] == "wired") {
    $f_p = "iframe_wired.php";
    echo "<iframe src="$f_p" name="$f_n" scrolling="$f_s" frameborder="$f_b" align="$f_a" height="$f_h" width="$f_w">
    </iframe>";
} else {
    exit();
}

    if ($_GET['cat'] == "wireless") {
        $f_p = "iframe_wireless.php";
        echo "<iframe src="$f_p" name="$f_n" scrolling="$f_s" frameborder="$f_b" align="$f_a" height="$f_h" width="$f_w">
..........................

View Replies !
If..else Loops
I need somebody to repair the looping..It only loops 2 times. I wanted it to loops at least 5 times and display only the last row for each employee. All the data i get from database HPTRX tables. Code:

View Replies !
Loops
I'm building a form using the <select> tags to display a group of categories and sub categories like so:

Parent
--->Sub cat
--------> Sub sub cat
Parent 2
---->Another sub cat

I've written the following script, but it seems inefficient to keep writing it out multiple times for each sub category but I can't figure out how I'd write a loop to do this automatically. Code:

View Replies !
While Loops?
I'm trying to while loop using a flat txt file and write the values out
into a form. I have 50-58 values to echo. Am I going to have to echo
each line of html. Or is there a way to make this work between the php.
Right now it wants to write the whole table over and over. Is my logic
screwed up? Code:

View Replies !
For And While Loops
Ive got a javascript that creates a slideshow of some images that i specify in such way:

fadeimages[0]="photo1.jpg"
fadeimages[1]="photo2.jpg"
fadeimages[2]="photo3.jpg"
...

and so on

I have been trying to make a php script that reads a folder and searches for images. with those images, it uses a loop to print each image in such way so that the javascript will be able to work! Code:

View Replies !
For While Loops
I downloaded a custom written PHP page which pulls data from an XML feed and displays the results on screen. Code:

View Replies !
Need Help W/using Loops With Templates
I'm starting to use templates for my site and was curious about how they handled loops. For example, let's say I have a HTML table like this:

<table width="750" border="0">
<tr>
<td>{ARTIST}</td>
<td>{SONG_TITLES}</td>
</tr>
<tr>
<td>{ALBUM_TITLE}</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>

And the PHP file then calls records from the database for each placeholder in a while loop like this...

$result=mysql_query("select * from music where id = '$album_id'");
while ($row = mysql_fetch_array($result))

{
$album_id=$row['album_id'];
$artist= $row['artist'];
$album_title= $row['album_title'];
$song_title=$row['song_title'];
}

Normally, I would do something like this in the php file to point the data to the placeholder....

$myTemplate->tag("Site_title",gettitle());

So...my question is...where would I place the call to the database and the while loop and point each placeholder. Would I do something like this...

getmusic();
$myTemplate->tag("Album_Title",$row['album_title']); OR
$myTemplate->tag("Album_Title",$album_title);

If anyone has experience with this, please help! Thanks!!

View Replies !
Mysql_data_see For For() Loops?
Am I right to say mysql_data_seek allows me to walk through a database
return as I would an array?

for ($1=0; $i < $num; $i++) {
mysql_data_see($result, $i);
$row = mysql_fetch_array($results);
}

I still haven't solved the problem I mentioned in another post (I can
only get the first row back from my returns), so I'm tempted to go
this route.

View Replies !
Goto Loops?
I had someone ask me this at work and I had no clue if it existed in PHP, so I'm wondering if any of you know. In most scripting languages, they have a goto command (as in mIRC) and you can specify different sections, i.e.PHP Code:

View Replies !
Conditional Loop
I have one table, "players" that has player info including start season (year). I then have a table for each season with player stats, i.e. games played etc called stats200X where X is the year obviously.

I have no problem with extracting data from the current year, but what I would like to do is get data from previous years too. I was thinking about doing something like:

(year) - (startyear), which for example could be 3.

I don't know where to begin, but I want to be able to loop though previous years so that, if tables exist of course, I could do

select * from stats{Y -1}
display
select * from stats{Y -2}
etc

Would I need to hard code this or is there a way of doing this though a conditional loop?


View Replies !
Conditional Login..
I have a form with a username & password field along with 3 radio buttons.

What I basically want to achieve is if radio button A is checked it will post the username & pass to a.php, If button B is checked it will post the username & pass to b.php and so on for button C.

View Replies !
Do...while Loops Forever
While attempting to alleviate a persistent but not consistent problem
with my database operation (DB2) I coded the do...while loop around my
odbc_connect. When $dbConn is false the first time, the program never
returns. This problem repeatable with or without the @ on the
odbc_connect call. I would someone pointing out my stupidity. I did
RTFM, including the examples, and was no further enlightened. Thanks in
advance.

function conn() {
global $schema, $database;
$schema = "is3";
$database = "animalst";
$dbuser = "db2inst1";
$dbpwd = "db2rules";
$ct = 0;
do {
$dbConn = odbc_connect($database,$dbuser,$dbpwd);
$ct += 1;
if($dbConn==False) { sleep(1); }
}
while(($dbConn==False) && ($ct<5)) ;
if ( $dbConn==False) {
printf("<br>The odbc_connect parameters were:[%s] [%s]
[%s]<br>
" , $database,$dbuser,$dbpwd);
printf("<br>Tried %d times<br>
",$ct);
showerror();
die("could not connect to $database");
}
return $dbConn;
}
?

View Replies !
Code WHILE Loops
A script is written to query a db and print the result on the screen.

$result = mysql_query("SELECT * FROM events",$db);
$myrow = mysql_fetch_array($result);
$type = $myrow['type'];
echo "Type = $type";
while ($myrow = mysql_fetch_array($result)
{
$type = $myrow['type'];
echo "Type = $type";}

Question: Is there a cleaner way of coding this loop (which works fine, btw)?

If I don't include the first fetch_array & echo statement, the first row of the table is not printed to the screen. Using: while ($result) makes an endless loop (gets stuck on the first record). Same thing for while ($myrow). I don't mind coding it like my example above, but it seems like this is a convoluted way of doing things.

View Replies !
WHILE Loops Twice, Only Want It To Loop Once...
I have a working script, but for some annoying reason, this script for counting attendance over time for a single member loops through the years twice...any idea why?:
PHP Code:

View Replies !
Queries Outside Loops?
It was suggested to me that to speed up some code I have for a multiple select box that I place my queries outside my loops. I can't say I have the foggiest clue on how to do that.
My original code looked like: PHP Code:

View Replies !
Checkboxes,conditional
Basically I have what seems to be a very small problem but I am driving ny self mad trying to figure out what the problem is. Here is what I have: I have a form with two checkboxes:

<input type="checkbox" name="medicalcheck" >
<input type="checkbox" name="dentalcheck" >

the form is posting the a php file, decision.php, that simple checks to see if the boxes have been checked and performs an operation in either case. Here is the code:

View Replies !
Once Conditional Causes Error, The Other Doesn't...why?
There are 2 if statements at the beginning of this code snippet.  The one that is currently commented out works while the one that is not commented out yields this error

Parse error: syntax error, unexpected '{' in C:xampphtdocsench2index4.php on line 106

I am just not seeing why. Code:

View Replies !
Loops And Arrays?
Does anyone know where an in depth tutorial is to learn about loops and arrays? One that will give good examples.

View Replies !
Conditional Structures
I am wondering about conditional structures and the depth of nesting allowed, if at all. For example I know I can do this: Code:

View Replies !
Forms + While Loops
i have a 5x5 grid filled with 25 Option Buttons, now i want to make a loop that circles through them to see which one is selected and then compares that to a number in the database to see if something should be done. Is this possible? if so how?

View Replies !
Conditional Form
I want to condtionally display an HTML form. I havnt got a clue how it can be done, I suppose its the same way as putting html tables in php, but I cant get it to work. Here is the condtion:

<?php 
 if (!empty($pk))
  {    

And here is the form:

<form action="google.php" method="GET" name="deleteForm" >
<input type="hidden" name="pk" value="<? echo $pk;?>">
<input type="submit" value="Delete">
</form>

View Replies !
For Loops With Equation
How would I make a script using for loops to figure out this equation: EDCBA x 4 = ABCDE

Each letter represents a number and i need to know what ABCDE is. Anyone know?

View Replies !
DBs, Arrays And Loops
I've got a database that I'm pulling records from. That works. I need to loop through each selected record, put it into an array and then output that array to a function.
I can loop. I can array. I can output a manually contructed array. I just cannot get the array to loop through the db records. Code:

View Replies !
For Loops - Uses Over And Over For Incrementing
I'm trying to0 learn PHP and keep running into what looks like an example. I'm not sure though if the $i is suppose to mean somthing of if it is just an example. Here is the common thing I am seeing for ($i o; $i<3; $i++ )

So am I correct in thinking this just an example that this author uses over and over for incrementing, or is it a predefined variable in PHP.

View Replies !
While Loops Does Not Display The First Row
This while loops does not display the first ror it gets from the mysql query. Can anyone tell me why? PHP Code:

$result = mysql_query("SELECT * FROM users");
if(!$result) {
    $error = true;
    $errormsg = "<p>Error running query: ".mysql_error()."</p>";
} else {
    $row = mysql_fetch_array($result);
    if(!$row) {
        $error = true;
        $errormsg = "<p>Could not get users: ".mysql_error()."</p>";
    } else {
        while($row = mysql_fetch_array($result)) {
            if($row["permissions"] == 1) {
                $user_permissions = "Normal";
            } elseif($row["permissions"] == 2) {
                $user_permissions = "Superuser";.....

View Replies !
PHP Conditional Include
I just set up a perl script that outputs a single html file. Works great, but I need to be able to customize that one file for different sections of the site. Specifically I need different navigation and heading on the page.

I'm not a programmer, but this sounds like I want a conditional include to show what I want when I want, right? If so, can anyone give me any idea how to get started with something like this? I figured I'd try with PHP because it sounds easier than fooling with perl.

Also, doesn't a conditional statement generally work from a variable or something else in the page that changes? If so, what do I do when the page stays the same and doesn't include variables?

View Replies !
Foreach, While Loops?
I have an array which consists of some MySQL data. What I'm trying to do is output the arrays 10 at a time... so here is a dirty example of what I'm looking for. for each 10 results, do this:

<begin tag>
result1, 2, 3, 4, 5, 6, 7, 8, 9, 10
</end tag>

<begin tag>
results11, 12, 13, 14, 15, 16
</end tag>

So for every "10 results", it needs to start a new set of tags. This will be in CSS div's.

View Replies !
Problem With The Way My Loops Are Set Up..
I'm trying to write whatever data is returned to an xml file. This works, but due to the way I have my loops set up (which is obviously incorrect), it keeps writing a new xml file for each record. I want all records to go into one single xml file. Code:

View Replies !
PHP Loops Problem.
I have set up the database, and in the database I have 2 tables so far, one is for the pictures categories which has the names of the categories, and the urls, and the other is for the pictures which has the title of the pictures, and filenames and description, so I linked them both with a associated primary/foreign key relationship. Code:

View Replies !
Include In Conditional
Why does this not work?

if (!$artnr) {
include "./smalltable.php";
}
else {
include "./bigtable.php";
}

Is this the best php group for this sort of question?

View Replies !
Loops And Variables
I'm developing a small application that needs to repeated call on a series of recordsets that are similarly named. What I would like to do is call these recordsets in turn, display the contents. Repeat for each of the of them.

Assuming I have recordsets name rset0, rset1 ... rset9. The recordsets themselves have been declared earlier. The following code doesn't work obviously but i hope shows what I am trying to achieve. Code:

View Replies !
If/Else Conditional Statment
I just started php yesterday and found a site with a good tutorial but there's a problem, the "If/Else" statment doesn't seem to work, don't know if it's wrong in the tutorial or what. Code:

View Replies !
Nested Loops
I think nested loops will do what I want, but I can't seem to get them right. I have two tables, members and casts. I run the following query which gets me the data I want to display using the following php: Code:

View Replies !
Double While Loops
I'm trying to fill a select box in the update form so that multiple values in the select box are highlighted if the user previously selected multiple values, one if they only selected one value, and zero if they didn't select any values. The main problem I'm having writing this code is that I need to draw the values for the select box from two tables: the sections table which populates the entire possible range of select box values and the sections_x table which includes only the values that have been selected. What I've come up with so far is a double while loop:

while ($row = mysql_fetch_array($result5)) {
$section_id = $row['section_id'];
$section = $row['section'];
while ($row = mysql_fetch_array($result8)) {
$section_id_x = $row['section_id'];
$date_id_x = $row['date_id'];
if ($section_id == $section_id_x) {
$option_block5 .= "<option value="$section_id" selected="selected">$section</option>";
} else {
$option_block5 .= "<option value="$section_id">$section</option>";
}
}
}

However, the select box is just showing up blank.

View Replies !
Conditional Redirection
I understand the header thing but wanna redirect to different pages based on values entered on the previous page.

View Replies !
OR Conditional Statement
I am trying to do this. But for some reason or does not work. How do you do an or statement with PHP?

if ($var == 8 or $var == 9) {
print "is eight or nine";
} else {
print "not eight or nine";
}

View Replies !
More Than 1 Conditional In A Function
This is a great function I use to echo timestamps as "how long ago" timeframe. This function rounds up the time to the smallest hour, so that 2:55 echos "2 hours ago". The only conditional in this function is Code:

if($difference != 1) $periods[$j].= "s";
and what it does is to add an "s" if the second, minute, hour... is not 1 (pluralization).

I need now to add another conditional so that for anytime greater than 5 hours and less than 24 hours it will echo just the word "Today". I tried many possibilities without much success. Code:

View Replies !
Loops In <tr> Rows
I have numerous images with different categories in a db. On the page I want to show a maximum of 4 <td> rows, then if there are more images in the category it starts a new <tr> and maximum 4 <td> rows. Say for example there are only 6 images for a category I would like the left over <td> rows to be <td>&nbsp;</td>

Can this be done? I currently use while ($myrow = mysql_fetch_array($result)) to show the results.b Hope that makes sense?

View Replies !
Arrays, Loops
i hv a code which allows a user to enter personal details. on top of that, it prompts user to enter no of entries of other names btwn1-10. upon entering eg 5, 5 sets of drop down lists will be shown for the user to select 5 different names. after tht, these records will be stored in mysql. each name has 3 fields (id, name, add).

as i did not know how to use for loops to rotate the records to be stored in the database, i used the long method of creating 10 fields in the database and simply store them inside. eg........ table_id_1, table_name_1, table_add_1, table_id_2......n so on...till 10. what should i do? it gets worse this method cos later part, i need to extract all records and do more queries.

View Replies !
Conditional Against A Variable
what is wrong with this statement? The $ session is defined on the page. $session;

if($row_test['P_ID'] = $session){echo'show value'}
elseif($row_test['P_ID'] <> $session){echo'do not value'}

View Replies !
Conditional Submit
I'm creating a subscription form and i like to know how to create an interactive submit button. What i want is a submit button which only can be used when they agree with the terms of conditions by checking a checkbox.

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved