php:使用count()获取1而不是0

bweufnob  于 2021-06-20  发布在  Mysql
关注(0)|答案(6)|浏览(276)

我正在为我的网站添加一个视图计数器。在代码中,我检查是否有一个ip与post的id相同。
例如,当post id为26,并且在我的ip表中没有id为26的ip时,它应该返回0,但返回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();
  }
szqfcxe2

szqfcxe21#

假设您正在使用pdo
在这里,您将使用准备好的语句来查询数据库,但不会获取数据库返回的结果
使用

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

更简单的方法

$checkIp->rowCount()

这将返回受查询影响的行数

agxfikkp

agxfikkp2#

$checkIp->execute(); 总是返回布尔值,所以这里的条件是错误的。检查这里的文件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();
}
u7up0aaq

u7up0aaq3#

在php文档中,execute retunr true或false

$checkIp->execute();

所以你的

(count($checkIp)

只需计算var内容,在这种情况下,它只包含一个值

bq8i3lrv

bq8i3lrv4#

$checkIp 是一个对象,并且将始终(假设准备成功)返回非零计数。你想要什么(假设你正在使用 mysqli )是 $checkIp->num_rows . 如果您正在使用 PDO ,你想要什么 $checkIp->rowCount() .

jgzswidk

jgzswidk5#

而不是这个

if (count($checkIp) > 0)

使用

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

c9x0cxw06#

这个 execute() 方法运行时,查询将返回一个布尔值,以确定查询是否成功。你可以用 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

相关问题