PHP:使用 count() 得到 1 而不是 0

PHP: getting 1 instead of 0 using count()

我正在为我的网站添加浏览量计数器。 在代码中,我检查是否有 ID 为 post.

的 IP

例如,当 post id 为 26 时,我的 IP table 中没有 ID 为 26 的 IP,它应该 return 0 但它 returns 1相反。

  $userIp = $_SERVER['REMOTE_ADDR'];
  $checkIp = $db->prepare("SELECT user_ip FROM user_ip WHERE word_id = '$idToShow'");
  $checkIp->execute();
//This happens
  if (count($checkIp) > 0) {
    echo count($checkIp);
    echo " ". $idToShow;
  }
//instead of this
  else {
    $insertIP = $db->prepare("INSERT INTO user_ip (user_ip, word_id) values('$userIp', '$idToShow')");
    $insertIP->execute();
    $updateView = $db->prepare("UPDATE words set views = views + 1 WHERE id = '$idToShow'");
    $updateView->execute();
  }

而不是这个

if (count($checkIp) > 0)

使用

if(isset($checkIp->user_ip) && !empty($checkIp->user_ip))

如 PHP doc 执行返回 TRUE 或 False

$checkIp->execute(); 

所以你的

(count($checkIp)   

只计算在本例中仅包含一个值的 var 内容

$checkIp 是一个对象并且总是(假设您的准备成功)return 非零计数。您想要的(假设您使用的是 mysqli)是 $checkIp->num_rows。如果您使用 PDO,则需要 $checkIp->rowCount()

$checkIp->execute(); 始终是 returns 布尔值,因此您的条件在这里是错误的。在此处查看文档 http://php.net/manual/en/pdostatement.execute.php 像这样使用

$userIp = $_SERVER['REMOTE_ADDR'];
$checkIp = $db->prepare("SELECT user_ip FROM user_ip WHERE word_id = '$idToShow'");
$result=$checkIp->execute();
if (!$result) {
    echo count($checkIp);
    echo " ". $idToShow;
}else {
    $insertIP = $db->prepare("INSERT INTO user_ip (user_ip, word_id) values('$userIp', '$idToShow')");
    $insertIP->execute();
    $updateView = $db->prepare("UPDATE words set views = views + 1 WHERE id = '$idToShow'");
    $updateView->execute();
}

假设您正在使用 PDO

这里你使用的是prepared statements来查询数据库,但是你并没有获取数据库返回的结果

使用

$result = $checkIp->setFetchMode(PDO::FETCH_ASSOC);
if(count($result) > 0){
  .............
}
else{
  ..........
}

更简单的你可以使用

$checkIp->rowCount()

这 returns 行数受您的查询影响

execute() 方法运行查询 returns 查询是否成功的布尔值。 您可以使用 rowsCount() 来计算行数,也可以使用 fetchAll() 然后计算结果。

你应该使用这样的东西

$checkIp->execute();
if ($checkIp && $checkIp->rowsCount() > 0) {
    // ...
}

$checkIp->execute();
$ips = $checkIp->fetchAll();
if (count($ips) > 0) {
    // ...
}

http://php.net/manual/en/pdostatement.execute.php
http://php.net/manual/en/pdo.prepare.php