2015-06-22 59 views
0

我有一個簡單的語句,但似乎無法從select語句中獲取行數,當它真的很簡單時真的讓我感到困擾。我不斷得到空串。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 
+2

[查看手冊](http://php.net/manual/en/pdostatement.rowcount.php)對於'$ conn-> rowCount'雖然它不完全可靠,因爲它不起作用,所有數據庫引擎 – RiggsFolly

+1

有一個方法:http://php.net/manual/en/pdostatement.rowcount.php,但不能保證與所有數據庫引擎一起工作。 – Koshinae

+0

那麼一定有另一種方式呢? – redoc01

回答

2

除了fetchColumn你可以嘗試以下方法:

  1. 計算行數

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

  2. 使用rowCount()

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

  3. 將它添加到查詢:在最後的查詢返回

    SELECT COUNT(*) as rowCount ...

    echo $row['rowCount'];

0

試試這個:

echo $q2->rowCount();

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

->rowCount();doc

+0

非上述工作 – redoc01

+0

@ redoc01它顯示了什麼錯誤? – alexandreferris

+0

沒有錯誤只是返回xcode上的空字符串 – redoc01

0

你總是可以得到的行數。剛過SELECT聲明

$sql2 = "select SQL_CALC_FOUND_ROWS * from TJ_ThreadJoined where TJ_T_ID = :threadID" 

然後執行查詢SELECT FOUND_ROWS()添加SQL_CALC_FOUND_ROWS,抓取行,你將有行數從去年的查詢。