【问题标题】:Why when I return a false value from a function the parent function gets it as true in php?为什么当我从函数返回假值时,父函数在 php 中将其设为真?
【发布时间】:2016-12-17 09:35:19
【问题描述】:

我是 PHP 新手,也许这是一个愚蠢的问题,但是当我使用函数检查数据库中是否存在记录时,使用以下命令:

function isGameExisted($con,$name) 
 {        
     $query = "SELECT * from Games WHERE NAME ='$name' LIMIT 1";
     $check = mysqli_query($con,$query);              
//       var_dump($check);
     if(mysqli_num_rows($check)){

       //echo " EXISTS ";
      return true;
     }else
     {      
     //echo " OFFER DOES NOT EXIST  ";   
     return false;  
     }
 }

到目前为止,它在名称不存在时返回 false

但在父函数中

$isExisting = isGameExisted($con,$name);
if($isExisting)
    {

       $json['Result'] = "Fail";
       $json['message'] = "Error in registering. Probably the name already exists";

    }else
    {

    }

我说实话了!消息注册时出错...我在这里缺少什么

谢谢

【问题讨论】:

  • isset($check) 将永远为真。这不是判断查询是否找到任何匹配项的方法。
  • 我应该尝试获取行数吗?
  • 您编辑了代码,但它与您已经收到的问题和答案不匹配。对于到达此页面的用户来说,这个问题现在毫无用处。您最好将问题恢复为初始文本。将答案中建议的更改应用于您的真实代码。
  • 不管怎样,结果都是一样的

标签: php


【解决方案1】:

问题是isset($check) 总是正确的。如果查询找到匹配行,$check 将被设置为一个数组。如果查询没有找到任何东西,$check 将被设置为NULL

你应该这样做:

return $check != false;

整个函数应该是:

function isGameExisted($con,$name) 
{        
     $query = "SELECT 1 from Games WHERE NAME ='$name' LIMIT 1";
     $check = mysqli_fetch_array(mysqli_query($con,$query));        
     return $check != null; 
}     

【讨论】:

  • 当我传递一条不存在的新记录时,它是假的,但在父函数中 $isExisting 变量是真的
  • 如果不存在则$check 为假,因此return $check != false 将返回false,而不是true
  • 是的,我告诉你如果它是假的,为什么 if($isExisting) { } else { } 不去其他部分?!?
  • ["current_field"]=> int(0) ["field_count"]=> int(9) ["lengths"]=> NULL ["num_rows"]=> int(0) [ “类型”]=> int(0) }
  • 这不对。这看起来就像您拨打$check = mysqli_query($query); 但没有拨打mysqli_fetch_array() 会得到的结果
【解决方案2】:
Please try with this

function isGameExisted($con,$name) 
 {        
     $query = "SELECT * from Games WHERE NAME ='$name' LIMIT 1";
     $excQuery = mysqli_query($con,$query);              
     if(mysqli_num_rows($excQuery)){
        //echo " EXISTS ";
          return true;
     }else
     {      
     //echo " GAME DOES NOT EXIST  ";    
     return false;  
     }       
 }

【讨论】:

  • 不使用$result,为什么还要打电话给mysqli_fetch_array
  • 我猜是业余的方法
  • 这个问题仍然适用。更改顺序并没有什么不同。
  • 如果你不想获取结果行,你可以评论/删除它。我只是把它放在那里。
  • 这就是我要问的:当它毫无用处时,你为什么要把它放在那里?您回答的重点是而不是调用mysqli_fetch_arraymysqli_num_rows,不是吗?
猜你喜欢
  • 2015-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-07
  • 1970-01-01
相关资源
最近更新 更多