<<

. 25
( 132 .)



>>


Since this is a book dealing with MySQL databases, we™ll show some examples of
if statements you can use when playing with database queries.
To test if a select query returned any rows, you can use either of the following:

$query = “select * from my_table”;
$result = mysql_query($query)or
die(mysql_error());
if (mysql_num_rows($result) > 0)
{
//do something here.
}



//this would also work
$query = “select * from test.foo”;
$result=mysql_query($query);
if (!($row = mysql_fetch_assoc($result)))
{
echo “there were no rows to fetch, so the query must have
returned no rows.”;
}

The following tests if an update query actually changed anything. A similar con-
struct would work for delete statements.

$query = “update mytable set col1=™my text™ where id = 1”;
mysql_query($query) or
die(mysql_error());
if (mysql_affected_rows() == 0)
{
echo “query did nothing”;
}

As is noted in Chapter 3, be careful to remember that the “equal to” operator is =
in MySQL, but == in PHP. A common typo is to write if ($a = $b) ... in PHP.
This assigns the value of $b to $a, and always tests as true, so it can be easy to miss.
Chapter 5: Control Structures 125


if ... else statements
If you™re clear on the previous sections, nothing here will surprise you. The else por-
tion of an if ... else statement enables you to specify code that will be executed
if the condition specified is false. The following code prints “it is not equal”:

$a = 2;
if ($a == 1)
{
echo “it™s equal”;
}
else
{
echo “it is not equal”;
}


if ... elseif statements
You will often have to check a variable against more than one set of conditions. For
instance, you might have a single page that will insert, edit, and delete records in a
database. It is fairly typical to indicate which portion of the script you wish to run
by assigning different values to a submit button in an HTML form. When the form
is submitted, the value of the submit button can be checked against several elseif
statements, as follows:

if ($_POST[˜submit™] == “edit”)
{
// code for editing database
}
elseif ($_POST[˜submit™] == “update”)
{
//code for updating records
}
elseif ($_POST[˜submit™] == “delete”)
{
//code for deleting records
}
else
{
echo “I have no idea what I should be doing.”;
}
126 Part II: Working with PHP


elseif is technically not the same as else if. If you put that space
between the words you will not get an error, but you could conceivably get
different behavior. In practice, the two variations are equivalent.




switch ... case
The switch structure is an alternative to multiple if ... elses. It won™t work for
everything, but in some situations switch will help you remove some ugly syntax.
Choose a variable against which you wish to run a comparison. Continuing the
example given in the discussion of if ... else, you may wish to execute differ-
ent parts of a script based on the value passed by a submit button:

switch ($_POST[˜submit™])
{
case “insert”:
// code to insert to database
break;
case “update”:
//code to update database
break;
case “display”:
//code to display
break;
default:
echo “Unexpected value {$_POST[˜submit™]} for ˜submit™\n”;
}

Here the code tests against the value in $_POST[˜submit™]. If the variable is
equal to “insert”, that portion of code is run.
Note the use of break in the preceding code. If break is not included, the code
will continue to run. For example, if $_POST[˜submit™] was equal to “update”,
the following would run the code for both the update and display portions:

switch ($_POST[˜submit™])
{
case “insert”:
// code to insert to database
break;
case “update”:
//code to update database
case “display”:
Chapter 5: Control Structures 127

//code to display
break;
}




Loops
No matter what programming language you™ve used in the past, you know that
loops are an essential part of programming. PHP has a rich set of loops that should
satisfy your every programming need.

while ...
This is probably the most common loop, so we™ll discuss it first. You give the while
loop a condition to validate. As long as that condition is true, the code within the
curly braces will be executed.

while (condition)
{
//code to execute here;
}

As a very basic example, the following code prints all the numbers between 0
and 10:

$a = 0;
while ($a<=10)
{
echo “$a <br> \n”;
$a++;
}

For something a bit more practical, you will use a while loop to iterate through
every row returned by a database query. Since mysql_fetch_assoc() will return
false if there™s no row to be fetched, it works quite nicely with a while loop.

$query = “select fname, lname from people”;
$result = mysql_query($query) or
die(mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo $row[“fname”] , “ “ , $row[“lname”] , “<br> \n”;
}
128 Part II: Working with PHP

USING while WITH list() = each()
Another place while ... often comes into play is with arrays, when you are using
the list() = each() structure. This structure assigns elements in an array to
named variables. It will iterate through the array, and when no more elements are
left to pull from, it will test false and the while loop will stop. When pulling from
an array, list() is expecting an associative array and will take two variables: the
first for the key and the second for the value, as illustrated in the following code:

$knicks = array (center => “Ewing”, point => “Childs”,
shooting_guard => “Houston”,
forward => “Sprewell”, strong_forward => “Johnson”
);
echo “<h2>The Knicks 1999 Starting Five Were</h2>”;
while (list($key,$value) = each ($knicks))
{
echo “$key: $value <br>\n”;
}



After you run the preceding code the array pointer will be at the end of the
array. If you wish to loop through it again, you will have to move the pointer
to the beginning of the array with reset. In the preceding example,
reset($knicks) would work.



Note that if you don™t have an associative array and you wish to grab array val-
ues, you will need to account for it in your list(). Do this by including a comma
within the list parentheses, as follows:

$names = array(“John”, “Jacob”, “Jason”, “Josh”);
while (list ( , $value) = each ($names))
{
echo “$value <br> \n”;
}

If no comma preceded $value in the preceding code, the ordinal placement of
each element would be assigned to $value and the code would print “0, 1, 2, 3”.
If you want to get only the keys out of an associative array, your list statement
should contain something like list($key, ).
Though we™re stressing list™s use with the each() statement, it can generally be
thought of as an “array destructor.” ” that is, it pulls elements out of an array.
Similarly, each() is an “array iterator,” meaning that it walks through all the ele-
ments in an array. It doesn™t need to be used with list(), though that is by far the
most common usage.
Chapter 5: Control Structures 129

USING MULTIPLE while LOOPS
Continuing with the subject of while loops and MySQL queries, you probably need
a quick piece of code that prints out the results of any query. For this, you can use
a nested set of while loops. The outer loop fetches each individual record from the
database, and the inner one prints out the contents of each individual record:

while($row = mysql_fetch_assoc($result))
{
while (list($key, $value) = each ($row))
{
echo “<b>$key:</b> $value <br>\n”;
}
}


do ... while
The do ... while loop is nearly identical to the while loop. The only difference is
that the condition is tested after the code in question has been run once, as follows:

do
{
//code to be used here.
} while (condition);

The preceding structure may be useful to you. It may even be vital to scripts you
need to write. But in the course of writing the large applications for this book, we
didn™t need to use it once.

for
The for loop takes three expressions.

— The first is evaluated once before the second expression is tested.

— The second argument is a condition that is evaluated each time through
the loop; if the condition in the second argument tests false, the loop ends
(or never begins if it tests false right away).
— The third expression is executed after the body of the loop is run.

As an example, the following code iterates through every value in an array and
prints the value for each element:

$myarray = array (˜jay™, ˜brad™, ˜john™, ˜kristin™);
for ($i = 0; $i < count($myarray); $i++)
{
130 Part II: Working with PHP

echo $myarray[$i] . “<br>\n”;
}

<<

. 25
( 132 .)



>>