使这个代码PDO友好

时间:2013-03-10 12:06:42

标签: php mysql pdo

我刚刚开始使用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(),但它似乎不起作用......

抱歉我的英语很差,我来自瑞典!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-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>";
   }
}