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

-------------Problems Reply------------

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.

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.

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

Category:php Views:1 Time:2010-08-01
Tags: php pdo

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.092 (s). 11 q(s)