使此代码对PDO友好


make this code PDO friendly

我刚刚开始使用PDO而不是mysql函数。但是现在我被我的php博客卡住了。

如何使这段代码更适合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(),但它似乎不工作…

对不起,我的英语很差,我来自瑞典!

rowCount在PDO中不能与mySQL一起工作。相反,您只需运行count(*)查询。

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

来源:行数与PDO

$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>";
   }
}