PDO help with prepare and execute statements

When using PDO with the prepare and execute statements, I keep on getting a “Fatal error: Call to a member function execute() on a non-object in about.php line 20” with this block of code. I tried following all the guides and I thought I had it right but I keep getting this error.

My PDO connection (username/pass changed from live of course):

$db_uname = "PHP";
$db_pass = "password";

$dsn = 'mysql:host=localhost';
$myPDO = new PDO($dsn, $db_uname, $db_pass);

// Database
$sql_main = 'Main';

And here is the code:

	  $acontent_c = $myPDO->prepare("SELECT COUNT(*) FROM $sql_main.content WHERE page='about' AND subpage=:subpvalue");
	  $acontent = $myPDO->prepare("SELECT * FROM $sql_main.content WHERE page='about' AND subpage=:subpvalue");

	  if (!empty($_REQUEST['area']) && $_REQUEST['area'] == "contact") {
		  $acontent_c->execute(array(':subpvalue' => 'contact'));
		  if ($acontent_c->fetchColumn() > 0) {
			  $acontent->execute(array(':subpvalue' => 'contact'));
			  $acontent_row = $acontent->fetch(PDO::FETCH_ASSOC);
			  echo '<p><a href="/about">Go back to About Us</a></p>';
			  echo $acontent_row['text'];

Strange. That usually indicates a spelling error for the variable name but it looks good to me. Check that the prepare statement is in in fact returning an object.

It might be having two prepare statements but I really wouldn’t think so. You don’t really need both of them. I would just use the second one, do a fetchAll and then test if the count > 0.

Did you add the PDO error mode variable setting? PDO is silent by default.

Thanks for your help. I ended up resolving it because the prepare statement was created in a previous elseif so obviously the execute(); had nothing to reference because the code didnt show it under that condition.

I think what is happening is that your query is throwing an error and hence your are not getting a statement object back.

you should add:

and maybe:

To make sure sql errors get shown.

And I’m not sure but I think you need to specify a database name when connecting:

It is telling me that “Notice: Undefined variable: acontent_c” but I thought I was defining it with the PDO statement?

About the database name, I have it set with the $sql_main which works on all the other pages. Just the prepare and execute are giving problems