Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using MySQL variable in PHP Prepared Statement

When using a SET clause in a MySQL statement, mysqli->prepare returns false.

This MySQL statement will "prepare" okay:

$query = "  INSERT INTO log (channel, message, context, datetime)
              VALUES (?, 'testmsg', '{}', CURRENT_TIMESTAMP); ";
  
  $stmt = $mysqli->prepare($query); // $stmt will be true

This statement will cause "prepare" to return false.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$query = " SET @Channel = ?;
           INSERT INTO log (channel, message, context, datetime)
           VALUES (@Channel, '', '{}', CURRENT_TIMESTAMP); "
$stmt = $mysqli->prepare($query); // $stmt will be false

The error is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘INSERT INTO log (channel, message, context, datetime) ‘ at line 2

Why can’t prepare handle the SET operator in MySQL in this manner? I want to list all my variables (this example only has one but imagine one with 10+) at the top of my statement for readability instead of sprinkling them inside the mysql code. That’s not very unreadable and difficult to debug.

>Solution :

You can only prepare one SQL statement at a time. But your $query contains two statements, separated by a semicolon. Split them apart, or just use this.

$query = " INSERT INTO log (channel, message, context, datetime)
           VALUES (?, '', '{}', CURRENT_TIMESTAMP); "
$stmt = $mysqli->prepare($query);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading