[Gloucs] mysql query in a php loop?
Guy Edwards
gloucs at mailman.lug.org.uk
Tue Jun 17 20:28:00 2003
Hi,
I've got a mysql/php coding problem.
my bit of PHP code goes something like this:
- do a MySQL query
- get results
for (each result)
{
if(something==somevalue)
{
if(some_condition)
{exit}
if(some_other_condition)
{exit}
update MySQL database to change relevant row which matches criteria
}
}
problem is, say there are 3 results that are to be processed (match the
criteria) , as soon as it hits the first one, it stops doing the loop.
It works perfect for one result but doesn't continue processing the
others after. (real code below)
Is this because you can't have a loop based on a MySQL query and then
have a MySQL query going on inside that loop? or have I just got it
wrong? If its fundamentally wrong could anyone give me a minor clue as
to what to look at to fix it?
Thanks
Guy
---------------
The code below is for something similar to a library loan system, but
you've selected multiple items to bookout at once.
require ("dbconnect.inc.php"); // usual connect to a database stuff
$query="SELECT itemid from item";
require ("get_results.inc.php"); // just gets the query results
for ($i=0; $i <$num_results; $i++)
{
$row = mysql_fetch_array($result);
$req_num = htmlspecialchars(stripslashes($row["itemid"]));
// check for submitted value
$bnum = $_POST["b$req_num"];
$bnum = addslashes($bnum);
if($bnum == "on")
{
// check if the part is already loaned out on the proposed date
$itemid = $req_num ;
require ("check_item_already_out.inc.php");
// check future loan dates
// is bookout date before currently loaned out date?
if($date_bookout < $check_loanout)
{
if($proposed_return > $check_loanout)
{ include("loan_error.inc.php"); }
/* cant bookout - halt with error message */
else
{ /* continue */ }
}
else
{
if($date_bookout > $check_proprtn)
{ /* continue */ }
else
{ include("loan_error.inc.php"); }
/* cant bookout - halt with error message */
}
// anything that got this far needs to be processed
// actual sql for bookout
$query = "INSERT INTO loan VALUES (
NULL,
'".$userid."',
'".$itemid."',
'".$date_bookout."',
'".$proposed_return."',
'".$actual_return."',
'".$comments."') ";
mysql_query($query) or die(mysql_error());
}
}
--
Guy Edwards <guy_j_edwards@hotpop.com>