0

I've just started using PDO instead of the mysql functions. But now I'm stuck on a part of my php blog.

How would I make this code a little more PDO friendly:

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

I tried with PDO rowCount(), but it doesn't seem to work...

Sorry for my poor english, I'm from Sweden!

ethrbunny
  • 10,379
  • 9
  • 69
  • 131
Kim Andersson
  • 251
  • 2
  • 4
  • 15

2 Answers2

0

rowCount doesn't work with mySQL in PDO. Instead, you just run the count(*) query.

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

Source: Row count with PDO

Community
  • 1
  • 1
Nate Higgins
  • 2,104
  • 16
  • 21
-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>";
   }
}
ethrbunny
  • 10,379
  • 9
  • 69
  • 131
  • Hi, that code displays the blog navigation, but I get an error to, "Warning: Illegal string offset 'num' in C:\wamp\www\meranhem\blogg.php on line 70". And line 70 is this line: "$total_results = $results[ 'num' ];" – Kim Andersson Mar 10 '13 at 12:24
  • try 'select count(*) num...' instead.. also - what's the output of 'print_r( $results, true );' ? – ethrbunny Mar 10 '13 at 12:27
  • If its to a web page - use 'view source' – ethrbunny Mar 10 '13 at 12:36