mysql查询结果的php if语句(检查查询是否返回任何内容)
我有一只虫子。。我想这可能是因为这个代码:mysql查询结果的php if语句(检查查询是否返回任何内容),php,mysql,Php,Mysql,我有一只虫子。。我想这可能是因为这个代码: $post = addslashes($post); $r = $conn->query("select id from Posts where post='$post'"); if($id = $r->fetch_assoc()["id"]){ echo 'greg!!!<br>'; } $post=addslashes($post); $r=$conn->query(“从post='$post'的post
$post = addslashes($post);
$r = $conn->query("select id from Posts where post='$post'");
if($id = $r->fetch_assoc()["id"]){
echo 'greg!!!<br>';
}
$post=addslashes($post);
$r=$conn->query(“从post='$post'的post中选择id”);
如果($id=$r->fetch_assoc()[“id”]){
回音“格雷格!!!
”;
}
我只是想回应“格雷格!!!”如果查询“select id from post where post='$post'”返回任何内容。我发现有时候这样行,有时候不行。。。所以不太确定。也许是报价问题?。。。但是我认为addslashes方法会处理这个问题$r->fetch_assoc()[“id”]
我认为这是行不通的,因为$r->fetch_assoc()
还不是数组。应该是这样的:
$post = addslashes($post);
$r = $conn->query("select id from Posts where post='$post'");
$fetch = $r->fetch_assoc();
if($id = $fetch["id"]){
echo 'greg!!!<br>';
}
或者使用
$r->num_rows
计算返回的行数。如果是PDO,则可以使用rowCount()
,如果是MySQLi,则可以使用num_rows
检查是否有返回的行
// PDO
if($r->rowCount() > 0){echo "greg";}
// MySQLi
if($r->num_rows > 0){echo "greg";}
错误说明了什么?您是否在这里使用条件
if($id=$r->fetch_assoc()[“id”])
我认为应该if($id=$r->fetch_assoc()[“id”])
?不获取错误。。。。但代码没有按预期运行。当我不应该的时候,我得到了重复的条目。至于==,我没有在任何地方预定义$id,我只是想看看查询是否返回任何结果,或者数据库中是否没有匹配项。为什么不检查mysqli_num_rows
,或者PDO等效项?谢谢!mysqli_num_行更干净,更明显。我想我的错误只是一个愚蠢的错误。我点错了要检查的东西。
// PDO
if($r->rowCount() > 0){echo "greg";}
// MySQLi
if($r->num_rows > 0){echo "greg";}