aaaaaa
aaaaaa

Reputation: 2618

Foreach loop brings to Fatal error: Call to a member function bindParam() on a non-object

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 ! =)

Upvotes: 0

Views: 950

Answers (3)

johannes
johannes

Reputation: 15989

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>';
}

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

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.

Upvotes: 2

Karel Petranek
Karel Petranek

Reputation: 15164

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.

Upvotes: 0

Related Questions