Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO Error (42000) [duplicate]

Tags:

php

mysql

pdo

I'm using PHP PDO to insert data into my database table which looks like so (called stb_committee_members):

Field        | Type
--------------------
id           | int (10) (unsigned)
stb_group_id | int (10) (unsigned)
name         | varchar(50) (can be null, default NULL)
position     | varchar(50) (can be null, default NULL)
from         | varchar(50) (can be null, default NULL)
experience   | varchar(50) (can be null, default NULL)
photo        | varchar(50) (can be null, default NULL)

and here is the code I'm using to insert into the database:

    $group_id = $dbh->lastInsertId();

    foreach ($committee_members as $committee_member) {
        $com_member_name = $committee_member['name'];
        $com_member_position = $committee_member['position'];
        $com_member_from = $committee_member['from'];
        $com_member_experience = $committee_member['experience'];
        $com_member_photo = $committee_member['photo'];

        $sth = $dbh->prepare("INSERT INTO stb_committee_members (stb_group_id, name, position, from, experience, photo) VALUES (?, ?, ?, ?, ?, ?)");
        $sth->bindParam(1, $group_id);
        $sth->bindParam(2, $com_member_name);
        $sth->bindParam(3, $com_member_position);
        $sth->bindParam(4, $com_member_from);
        $sth->bindParam(5, $com_member_experience);
        $sth->bindParam(6, $com_member_photo);
        $sth->execute();
    }

This is the error message I get:

array(3) {
  [0] => string(5) "42000"
  [1] => int(1064)
  [2] =>
      string(226) "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 'from, experience, photo) VALUES ('37', 'gfdgdf', 'gfdg', 'gfdgfd', 'gfdggfd', '1' at line 1"
}

object(PDOStatement)#3 (1) {
  ["queryString"] =>
  string(115) "INSERT INTO stb_committee_members (stb_group_id, name, position, from,     experience, photo) VALUES (?, ?, ?, ?, ?, ?)"
}

And the values I'm trying to post are (in order):

string(2) "37"
string(6) "gfdgdf"
string(4) "gfdg"
string(6) "gfdgfd"
string(7) "gfdggfd"
string(20) "1314261618-acida.png"

I just can't see what's wrong! All of my other inserts are working fine, and created in the same way...

like image 640
Becky Avatar asked Feb 23 '23 04:02

Becky


1 Answers

from is a reserved keyword in SQL, you must quote it using backticks.

$sth = $dbh->prepare("INSERT INTO stb_committee_members (stb_group_id, name, position, `from`, experience, photo) VALUES (?, ?, ?, ?, ?, ?)");
like image 137
ThiefMaster Avatar answered Mar 03 '23 18:03

ThiefMaster