Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly make a PDO statement with PHP variables as parameters?

I currently have the following code:

$dbh = new PDO('mysql:host='.DATABASE_HOST.';dbname='.DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$dbh->prepare("INSERT INTO mdr_contacts SET fkRelatieId = 0, reseller = 0, code = :code, naam = :naam");
$dbh->execute(array(":code" => $contact["contact_id"],":naam" => $name));

However this seems to fail: Fatal error: Call to undefined method PDO::execute() in file.php on line 67

What i've done so far to make this work:

  1. Checked if $name and $contact exists and has the right value.
  2. Executed a SELECT query before the prepare statement to make sure that PDO works.
  3. Runned the code without ATTR_EMULATE_PREPARES set to false.

But none of this works, can anyone set me in the right direction?

like image 347
RTB Avatar asked Nov 21 '25 07:11

RTB


1 Answers

You execute a statement, not a connection. prepare() on a connection, returns a statement.

Also, I prefer to explicitly call bind on values, but this is just my OCD prefs.

 $statement = $dbh->prepare("INSERT INTO mdr_contacts SET fkRelatieId = 0, reseller = 0, code = :code, naam = :naam");
 $statement->bindValue(":code", $contact["contact_id"]);
 $statement->bindValue(":naam", $name);
 $statement->execute();
like image 166
Ray Avatar answered Nov 22 '25 19:11

Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!