$sql = "SELECT count(name) FROM `TABLE` WHERE name='$name' ";
$sth=$conn->prepare($sql);
$totalrows = $sth->fetch(PDO::FETCH_ASSOC);
echo "$totalrows";
这是我的代码来计算使用PHP PDO准备语句行的总数,但$totalrows
回声什么,它没有价值。这段代码中的错误是什么?PHP PDO Preprared行计数不工作
$sql = "SELECT count(name) FROM `TABLE` WHERE name='$name' ";
$sth=$conn->prepare($sql);
$totalrows = $sth->fetch(PDO::FETCH_ASSOC);
echo "$totalrows";
这是我的代码来计算使用PHP PDO准备语句行的总数,但$totalrows
回声什么,它没有价值。这段代码中的错误是什么?PHP PDO Preprared行计数不工作
您需要:
# 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关于准备,绑定和执行。
更好的方法是使用'GROUP BY' COUNT()'如果你只想得到记录的总数。 – itzmukeshy7
使用查询后计算,并使用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();
解析错误:语法错误,意外的'私人'(T_PRIVATE) – Josh
尝试
$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();
现在$行是包含了结果阵列,使得
echo count($rows);
如果您有兴趣的记录总数只有这样,你不应该从数据库读取的所有记录尝试GROUP BY
从句,然后使用COUNT()
$sql = 'SELECT COUNT(name) AS totalRecords FROM `TABLE` WHERE name = ? GROUP BY name';
$stmt = $conn->prepare($sql);
$stmt->execute(array($name));
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch(); /* This will return a single record. */
echo 'Total records: ' . $row['totalRecords'];
您n eed to'$ sth-> execute();'(参见手册http://php.net/manual/en/pdostatement.execute.php示例#2),您可能需要绑定参数......取决于哪里' $ name'来自。另外使用'print_r($ totalrows);'不''echo $ totalrows;'。 '$ totalrows'将会是一个像'$ totalrows ['count()']'或类似的键的数组。 – Rasclatt
这个可怕的代码来自哪里? https://stackoverflow.com/questions/44485101/how-to-count-rows-from-mysql-with-pdp-pdo-prepared-statement – chris85