Forum Moderators: coopster

Message Too Old, No Replies

Database Query within a loop

query database mysql

         

dnsdeveloper

8:26 pm on Sep 24, 2007 (gmt 0)

10+ Year Member



Hi

I am new to this but familiar with J2EE etc development ... I am trying to iterate through an array of inputs and validate whether each exists in the database ... so I loop through and run a select statement against the database, and based on that I take the appropriate action ... what is happening is that only the first query is ran (first run through the loop) .. I am guessing it it because I can not re-use the $rows123 array? is that correct? what is the right way to do this?

below is my code:

for($j = 0;$j < count($TO_ARRAY);$j+=1){

$email = trim($TO_ARRAY[$j]);
$rows123 = array();

$query = "SELECT FIRST_NAME , LAST_NAME , E_MAIL FROM MEMBER where E_MAIL = '".$email."'";

echo $query;

$rows123 = getRecords($query);

echo $rows123[$j][0];
echo $rows123[$j][1];
echo $rows123[$j][2];
echo '<br>';

the GetRecords method is:

function getRecords($query) {
$rows = array();
$line = array();
$result = mysql_query($query);
if($result!= false ) {
if( mysql_num_rows($result)!=0 ) {
while ($line = mysql_fetch_array($result, MYSQL_NUM)) {
$rows[] = $line;
}
}
}
mysql_free_result($result);
return($rows);
}

Thanks for your help!

henry0

9:01 pm on Sep 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld!

Not sure I understand what you try to achieve :)
Try something in that range

for($j = 0;$j < count($TO_ARRAY);$j+=1){
while($email = trim($TO_ARRAY[$j]);
//$rows123 = array();

$query = "SELECT FIRST_NAME , LAST_NAME , E_MAIL FROM MEMBER where E_MAIL = '".$email[$j]."'";

//echo $query;

$email = getRecords($query);

echo $email[$j];
echo '<br>';
}

dnsdeveloper

9:30 pm on Sep 24, 2007 (gmt 0)

10+ Year Member



Thanks henry0!

I have perviously echoed the queries and they are properly formatted and return the right results when ran through the PHPAdmin ... but for some reason only the first one is ran through the code I had shown.

I am getting an array of emails, I iterate through them and basically run a query for each ...

do I need to somehow reset the result set? is that why?

the inputs are absolutely correct.

I have been looking for ways to clear the cache and all hence all array() and other things ...

is it generally possible to run queries using the same $rows123 (example) parameter?

Thanks for your help again