我正在尝试检查mysql_fetch_array()函数是否返回空数组。但我的代码似乎不起作用。在这里,我想确保如果数组为空,我想显示正在构建的消息。
代码:
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
while($fetchSet = mysql_fetch_array($exeQuery)) {
if(count($fetchSet) == 0) {
echo "This Page is Under Construction";
}else{
// something else to display the content
}
}
我该如何检查以获得这样的功能?
使用mysql_num_rows来计算行数。试试这个。
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows($exeQuery)== 0){
echo "This Page is Under Construction";
}
else{
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}
}
您确实应该使用mysql_num_rows
http://us2.php.net/manual/en/function.mysql-num-rows.php
但是,附带说明一下,您应该使用phpempty()
。http://us2.php.net/empty
当您使用mysql_fetch_array()时,它会返回数据中的行在使用while循环时逐个设置。
如果没有记录,while循环将不会执行。在这种情况下,声明一个布尔变量,如果它进入while循环,则将其设为true。类似:
$queryContents= queryMembers(); $exeQuery = mysql_query($queryContents); $recordExists = 0; while($fetchSet = mysql_fetch_array($exeQuery)) { if($recordExists == 0 ) $recordExists = 1; // something else to display the content } if($recordExists == 0 ){ echo "This Page is Under Construction"; }
希望这能奏效
您可以这样做:
while($r[]=mysql_fetch_array($sql));
// now $r has all the results
if(empty($r)){
// do something
}
来源:php-doc
如果没有结果,while循环中的代码永远不会运行。如果没有更多结果,mysql_fetch_array将返回null/false。你需要做的是先检查mysql_num_rows,然后再检查。
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows ($exeQuery) == 0) {
echo "This Page is Under Construction";
}
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}
试试这个
if(empty($fetchSet)
{
echo "This Page is Under Construction";
}
else
{
// something else to display the content
}