2017-06-12 55 views
0
$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行計數不工作

+1

您n eed to'$ sth-> execute();'(參見手冊http://php.net/manual/en/pdostatement.execute.php示例#2),您可能需要綁定參數......取決於哪裏' $ name'來自。另外使用'print_r($ totalrows);'不''echo $ totalrows;'。 '$ totalrows'將會是一個像'$ totalrows ['count()']'或類似的鍵的數組。 – Rasclatt

+0

這個可怕的代碼來自哪裏? https://stackoverflow.com/questions/44485101/how-to-count-rows-from-mysql-with-pdp-pdo-prepared-statement – chris85

回答

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關於準備,綁定和執行。

+0

更好的方法是使用'GROUP BY' COUNT()'如果你只想得到記錄的總數。 – itzmukeshy7

-2

得到計數修改代碼: 更換

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

隨着

$totalrows = $sth->fetchColumn(); 
+2

不工作兄弟。 – Josh

+0

你得到的錯誤是什麼? –

+0

沒有錯誤,只是不工作 – Josh

-2

使用查詢後計算,並使用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(); 
+0

解析錯誤:語法錯誤,意外的'私人'(T_PRIVATE) – Josh

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(); 

現在$行是包含了結果陣列,使得

echo count($rows);  
0

如果您有興趣的記錄總數只有這樣,你不應該從數據庫讀取的所有記錄嘗試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'];