How to check with php/sql if any of fields in database that are selected in while loop is 0?
$res = mysql_query('SELECT id, name FROM table'); \\check here?
while($row = mysql_fetch_array)
{
\\or check here?
开发者_StackOverflow社区}
Thanks in advance!
EDIT: I need to select all fields and then check if any one of them is 0.
$foundZero = false;
$res = mysql_query('SELECT id, name FROM table');
while ($row = mysql_fetch_array($res))
{
if (in_array(0, $row))
{
// This row has a zero
$foundZero = true;
}
}
if ($foundZero)
{
// at least one zero in one row has been found
}
else
{
// No zeros have been found
}
If $foundZero
is true, then at least one field in one row is equal to 0. Otherwise, all fields are non-zero.
in the query add a where clause
SELECT id, name FROM table where my_field=0
then you not need to check every results, you get only the wanted results rows.
Obviously, check inside the while loop. For the query may return ZERO row.
$res = mysql_query('SELECT count(*) FROM table WHERE my_field=0'); \\check here?
if(mysql_num_rows($res) > 0)
{
while($row = mysql_fetch_array)
{
\\or check here?
}
}
If you really have to return all rows and then check for zero, add an order by clause to your query to minimize your checking.
SELECT id, name FROM table ORDER BY id DESC
then
if ($id <= 0)
handleIt()
else
proceed()
精彩评论