在整数中调用成员函数fetch()

时间:2018-09-12 13:45:08

标签: php pdo

我对以下简单的pdo查询有疑问:

$NU=$connection->exec("SELECT COUNT(ID) AS Total FROM USERS");
$Result=$NU->fetch(PDO::FETCH_ASSOC)['Total'];
echo "$Result";

由于我在查询中没有要绑定的参数,因此在没有exec的情况下使用prepare是正确的,如何解决此问题? (Call to a member function fetch() on integer in

4 个答案:

答案 0 :(得分:1)

exec()方法仅返回生效的行数。您可能想改用query()

$NU=$connection->query("SELECT COUNT(ID) AS Total FROM USERS");
$Result=$NU->fetch(PDO::FETCH_ASSOC)['Total'];
echo "$Result";

query()语句将执行一个查询,并返回一个PDOStatement对象,您可以从中获取该对象,或者在失败时返回false

答案 1 :(得分:1)

您需要使用query http://php.net/manual/en/pdo.query.php,然后会有一个对象,可以使用其结果。

答案 2 :(得分:0)

尝试一下。

<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
  <input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
  <input type="radio" id="chair-1" name="chair" class="chair" value="-1">
  <input type="radio" id="car1" name="car" class="car" value="1">
  <input type="radio" id="car0" name="car" class="car" value="0" checked>
  <input type="radio" id="car-1" name="car" class="car" value="-1">
  <input type="radio" id="house1" name="house" class="house" value="1">
  <input type="radio" id="house0" name="house" class="house" value="0" checked>
  <input type="radio" id="house-1" name="house" class="house" value="-1">
  <input type="radio" id="tree1" name="tree" class="tree" value="1">
  <input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
  <input type="radio" id="tree-1" name="tree" class="tree" value="-1">
  <input type="radio" id="flower1" name="flower" class="flower" value="1">
  <input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
  <input type="radio" id="flower-1" name="flower" class="flower" value="-1">
  <input type="radio" id="grass1" name="grass" class="grass" value="1">
  <input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
  <input type="radio" id="grass-1" name="grass" class="grass" value="-1">
  <div> <input type="button" value="Search" id="filter"/> </div>
</form>
<div id="output2"></div>

答案 3 :(得分:-1)

您要查找的不是exec,而是prepare。从PHP文档:http://php.net/manual/en/pdostatement.fetch.php

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);