如何在 PHP 中检查表行是否为空


How to check a table row is empty in PHP?

我想检查一行在 PHP 中是否为空。如果"$jfeta 3"不为空,则给出"成功"的值,否则转到其他部分。在 else 部分中,如果 "$jfeta['rate_number']" 大于 0,则给出 "Success2" 的值,否则给出 "Success3" 的值。但所有值都同时打印(成功、成功 2 和成功 3(。我一次只想打印一个值。

这是我的PHP代码。

$product_id = mysql_real_escape_string($_GET['p']);
$jsqla = mysql_query("select * from products where id='$product_id'") or die(mysql_error());
$jfeta = mysql_fetch_assoc($jsqla);
$product_id = $jfeta['id'];
$jsqla3 = mysql_query("select * from user_star_rate where product_id='$product_id' and      email='$visit_email'") or die(mysql_error());
$jfeta3 = mysql_fetch_assoc($jsqla3);
if(!is_null($jfeta3)) {
   $ratea = $jfeta3['rate_value'];
   echo "Success = ".$ratea;
   $rateid = $jfeta['id'];
   $arate_num = $jfeta['rate_number'];
} else {
   $arate_num = $jfeta['rate_number'];
   if($jfeta['rate_number'] > 0){ 
       $ratea = $jfeta['rate_score'] / $jfeta['rate_number']; 
       echo "Success2 = ".$ratea;
       $ratea2 = $jfeta['rate_score'];
       $rateid = $jfeta['id'];
       $ratenum = $jfeta['rate_number'];
   }else{ 
       $ratea = $jfeta['rate_score']; 
       echo "Success3 = ".$ratea;
       $ratea2 = $jfeta['rate_score'];
       $rateid = $jfeta['id'];
       $ratenum = $jfeta['rate_number'];
   }
}

is_null()用于检查值是否null,而不是空。要查看值是否为空,请使用empty()

if(!empty($jfeta3)) {

应该注意的是,null值被视为空值,并且将无法通过此检查。其他空值包括:

  • "(空字符串(
  • 0
  • (0 作为整数(
  • 0.0(0 作为浮点数(
  • "0"(0 作为字符串(
  • array(( (一个空数组(
  • $var;(已声明但没有值的变量(

你的错误在这里:if (!is_null($jfeta3)) . is_null()检查值是否为空,而不是空。 只需使用 if ($jfeta3) . 如果值为 null,则不会执行该语句,如果该值为空,则该语句仍将不执行。

使用 if($jfeta3) .它检查语句是否为 null。如果它不为 null 或不为空,则执行 if 部分,否则执行 else 部分。

或者

你可以尝试使用mysql_num_rows() > 0来替换!is_null()。我试过这段代码:

$product_id = mysql_real_escape_string($_GET['p']);
$jsqla = mysql_query("select * from products where id='$product_id'") or die(mysql_error());
$jfeta = mysql_fetch_assoc($jsqla);
$product_id = $jfeta['id'];
$jsqla3 = mysql_query("select * from user_star_rate where product_id='$product_id' and      email='$visit_email'") or die(mysql_error());
$jfeta3 = mysql_fetch_assoc($jsqla3);
if((mysql_num_rows($jsqla) > 0) && (mysql_num_rows($jsqla3) > 0)) {
   $ratea = $jfeta3['rate_value'];
   echo "Success = ".$ratea;
   $rateid = $jfeta['id'];
   $arate_num = $jfeta['rate_number'];
} else {
   $arate_num = $jfeta['rate_number'];
   if($jfeta['rate_number'] > 0){ 
       $ratea = $jfeta['rate_score'] / $jfeta['rate_number']; 
       echo "Success2 = ".$ratea;
       $ratea2 = $jfeta['rate_score'];
       $rateid = $jfeta['id'];
       $ratenum = $jfeta['rate_number'];
   }else{ 
       $ratea = $jfeta['rate_score']; 
       echo "Success3 = ".$ratea;
       $ratea2 = $jfeta['rate_score'];
       $rateid = $jfeta['id'];
       $ratenum = $jfeta['rate_number'];
   }
}