PHP - PDO,如何返回select语句中的行数

时间:2015-06-22 13:30:39

标签: php pdo

我有一个简单的声明,但似乎无法从select语句中获取行数,当它非常简单时真的很烦我。我一直在变空。

这是代码

include "connect.php";

$userID = $_POST['userID'];
$threadID = $_POST['threadID'];

$sql1 = "select * from AT_AddThread where AT_ID = :threadID";
$stmt = $conn->prepare($sql1);
$stmt->execute(array(':threadID' => $threadID));
$result = $stmt->fetchColumn(7);
//echo $result;

$sql2 = "select * from TJ_ThreadJoined where TJ_T_ID = :threadID"
$q2 = $conn->prepare($sql2);
$q2->execute(array(':threadID' => $threadID));
$q2->execute();
$rows = $q2->fetchColumn();
echo $rows; //THIS IS where i want to return the number of rows from the select statement

3 个答案:

答案 0 :(得分:2)

除了fetchColumn,您还可以尝试以下方式:

  1. 计算行数

    $rows = $stmt->fetchAll(); echo "count = " . count($rows);

  2. 使用rowCount()

    echo "count = " . $stmt->rowCount();

  3. 将其添加到查询中:

    SELECT COUNT(*) as rowCount ...

    echo $row['rowCount'];

答案 1 :(得分:0)

试试这个:

Telephone

echo $q2->rowCount();

$row = $q2->fetch(PDO::FETCH_NUM); echo $row[0]; doc

答案 2 :(得分:0)

您始终可以获取上次查询中返回的行数。只需在SQL_CALC_FOUND_ROWS声明

之后添加SELECT即可
$sql2 = "select SQL_CALC_FOUND_ROWS * from TJ_ThreadJoined where TJ_T_ID = :threadID"

然后执行查询SELECT FOUND_ROWS(),获取行,您将获得上次查询的行数。