PHP PDO预备红外行计数不起作用

时间:2017-06-12 03:26:53

标签: php mysql pdo

$sql = "SELECT count(name) FROM `TABLE` WHERE name='$name' ";
$sth=$conn->prepare($sql);
$totalrows = $sth->fetch(PDO::FETCH_ASSOC);

echo "$totalrows";

这是我使用PHP PDO Prepare语句计算总行数的代码,但$totalrows没有回显,它没有任何价值。这段代码有什么错误?

5 个答案:

答案 0 :(得分:2)

你需要:

# USE "as count" here so it's easy to reference
$sql = "SELECT count(name) as count FROM `TABLE` WHERE name = :name";
# prepare as you have
$sth = $conn->prepare($sql);
# Bind parameters while executing
$sth->execute(array(':name'=>$name));
# Fetch the associate array
$totalrows = $sth->fetch(PDO::FETCH_ASSOC);
# Echo the count
echo $totalrows['count'];

在准备,装订和执行方面审核Example #2 from the manual

答案 1 :(得分:1)

尝试

$sql = "SELECT count(name) FROM `TABLE` WHERE name=? ";
$stmt=$conn->prepare($sql);
$stmt->execute(array($name));
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = $stmt->fetchAll();

现在$ rows是一个包含结果的数组

echo count($rows);      

答案 2 :(得分:0)

如果您只对记录总数感兴趣,那么您不应该从数据库中获取所有记录,请尝试list(skip=0, limit=50)子句,然后使用GROUP BY

COUNT()

答案 3 :(得分:-2)

要获取计数,请将代码修改为: 取代

$totalrows = $sth->fetch(PDO::FETCH_ASSOC);

使用

$totalrows = $sth->fetchColumn();

答案 4 :(得分:-2)

在查询后使用count并使用bind_param,这样就不会直接从用户那里收到输入:

$stmt = $conn->prepare("SELECT 'something' FROM 'somewhere' WHERE 'name' =  :name;

//get the user input thru a method and bind it to :name

private $name;

getName($name){

$this->name = $name;
}

$stmt->bindParam(':name');

 $stmt->execute();