tags:

views:

45

answers:

3

Hi there,

That's the first time i get an error like this one, let me explain :

Here is my code :

function printSiteIndexedItems($co, $id){
  global $allSections;
  foreach($allSections as $aSection => $aSectionName){
   $tr = $co->prepare("SELECT COUNT(id) FROM ". $aSection ." WHERE site=:id AND valide=1");
   $tr->bindParam(':id', $id, PDO::PARAM_INT);
   $tr->execute();
   if($indexedItems = $tr->fetchColumn()) echo '<p>'. $aSectionName .' : '. $indexedItems .'</p>';
  }
 }

The first iteration works just fine, it prints what i want (a category name and the number of elements in it).

But after that first iteration, i get this classic error :

Fatal error: Call to a member function bindParam() on a non-object in

Indeed, $co is a valid PDO object as it works for the first iteration. But it seems that as soon as we enter the second one, it no longer is ? :o

I'm kinda new with PDO, so maybe it's a normal behavior i didn't acknowledge yet. Please help ! =)

A: 

I think that $co->prepare returns a failure (false probably) which suggests that the statement is invalid. Make sure that $aSection is not empty.

You also shouldn't be putting $aSection to the query like you do now as you might encounter a SQL injection problem if $aSection comes from a user input.

dark_charlie
I already made sure $aSection was not empty, and tested the SQL request for every possible $aSection :/And $aSection doesn't come from a user input, i'm stuck but not lacking good practices :p
Pioul
+2  A: 

Looks like $co->prepare... returns FALSE for at least one of the stamtents you try to prepare.
Either test if ( !$tr ) .... or set $co->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); to get an exception when PDO encounters an error.

VolkerK
Thanks for the `$co->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);` ! Thanks to the error message i had, which told me to use `fetchAll()` instead of `fetchColumn()`, it know WORKS ! But i still don't get why i had to use `fetchAll()`, as my requests only return one row ..
Pioul
A: 

Most likely $aSection is invalid. As you didn't provide the data it is hard to guess. please learn about PDO error handling: http://de.php.net/manual/en/pdo.error-handling.php

something like this code should help:

foreach($allSections as $aSection => $aSectionName){
   $tr = $co->prepare("SELECT COUNT(id) FROM ". $aSection ." WHERE site=:id AND valide=1");
   if (!$tr) {
       print_r($co->errorInfo());
       continue;
   }

   $tr->bindParam(':id', $id, PDO::PARAM_INT);
   $tr->execute();
   if($indexedItems = $tr->fetchColumn()) echo '<p>'. $aSectionName .' : '. $indexedItems .'</p>';
}
johannes
Arf, `print_r(errorInfo());` didn't work, but `print_r($co->errorInfo());` actually does, i realized that after taking a look at your link (i guess it was a typing error). Thanks anyway !
Pioul
Fixed the code above. Your welcome.
johannes