2013-03-10 92 views
0

我剛開始使用PDO而不是mysql函數。但現在我被困在我的PHP博客的一部分。使此代碼PDO友好

我怎麼會做這個代碼更PDO友好:

$total_results = mysql_fetch_array(mysql_query("SELECT COUNT(*) as num 
    FROM php_blog")); 
$total_pages = ceil($total_results['num']/$blog_postnumber); 
for($i = 1; $i <= $total_pages; $i++) { 
    if ($page == $i) { 
     echo "<span class='current'>$i</span>"; 
    } 
    else { 
     echo "<a href=\"index.php?page=$i\">$i</a>"; 
    } 
} 

我PDO rowCount時()試過了,但它似乎並沒有工作...

對不起,我可憐的英語,我來自瑞典!

+0

喲不需要'rowCount時()',你需要'fetchColumn()'。你究竟試過了什麼? – 2013-03-10 12:08:17

回答

-1
$stmt = $db->exec("select count(*) as num from php_blog"); 
$results = $stmt->fetch(); 
$total_results = $results[ 'num' ]; 
$total_pages = ceil($total_results/$blog_postnumber); 
for($i = 1; $i <= $total_pages; $i++) { 
    if ($page == $i) { 
     echo "<span class='current'>$i</span>"; 
    } 
    else { 
    echo "<a href=\"index.php?page=$i\">$i</a>"; 
    } 
} 
+0

呃哦..我做錯了什麼? – ethrbunny 2013-03-10 12:20:05

+0

嗨,該代碼顯示博客導航,但我得到一個錯誤, 「警告:在C:\ wamp \ www \ meranhem \ blogg.php在70行非法字符串偏移量'num'」。第70行是這一行:「$ total_results = $ results ['num'];」 – 2013-03-10 12:24:10

+0

try'select count(*)num ...'instead。另外 - 'print_r($ results,true)'的輸出是什麼;'' ? – ethrbunny 2013-03-10 12:27:32

0

rowCount不適用於PDO中的mySQL。相反,您只需運行count(*)查詢。

<?php 
$sql = "SELECT count(*) FROM `table` WHERE foo = bar"; 
$result = $con->prepare($sql); 
$result->execute(); 
$number_of_rows = $result->fetchColumn(); 

來源:Row count with PDO

+0

爲什麼基於其他[錯誤]答案的這個答案是否被提升? – 2013-03-10 12:18:20

+0

這是怎麼回事? – Nathaniel 2013-03-10 12:23:52