简体   繁体   中英

Loop through array, query each value until certain condition is met

I'm a bit of a newb to PHP and MySQL. I seem to be having an issue with something. How do I loop through an array, querying each value in the array until the query meets a certain condition.. In this case it would be that the number of rows returned from the query is less than five. Here is what I have:

$query1="SELECT UserID FROM Users where RefID='$userid'";
$result1=mysql_query($query1);
while ($row = mysql_fetch_array($result1, MYSQL_NUM) && $sql2querynum < '5')
{
echo ($row[0]);
echo "
";
$sql2 = "SELECT * FROM Users WHERE RefID=$row[0]";
$sql2result = mysql_query($sql2);
$sql2querynum = mysql_numrows($sql2result);
}

Problem is, for every value it echoes out, I get the following warning: mysql_numrows(): supplied argument is not a valid MySQL result resource

Like I said, I'm a newb, so maybe I'm not even going about doing this the right way.

try this

$query1="SELECT UserID FROM Users where RefID='$userid'";
$result1=mysql_query($query1);
if(mysql_num_rows($result1)<5)
{
while ($row = mysql_fetch_array($result1))
{
echo ($row[0]);
echo "
";
$sql2 = "SELECT * FROM Users WHERE RefID=$row[0]";
$sql2result = mysql_query($sql2);
$sql2querynum = mysql_numrows($sql2result);
}
}
$query1="SELECT UserID FROM Users where RefID='$userid'";
$result1=mysql_query($query1);
while ($row = mysql_fetch_array($result1, MYSQL_NUM) && $sql2querynum < '5')
{
echo ($row[0]);
echo "
";
$sql2 = "SELECT * FROM Users WHERE RefID={$row[0]}";
$sql2result = mysql_query($sql2);
$sql2querynum = mysql_numrows($sql2result);
}

Use { } for variables in " " ... and why you are not using joins ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM