简体   繁体   中英

PHP/PDO SQLSTATE[42000]: Syntax error or access violation: 1064 Nightmare

I'm building an autocomplete dropdown box and I have a functional SQL call that will find what I'm searching for but when I try to integrate it into a proper PDO statement I can't shake this error message:

Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 'AND city LIKE CONCAT('van', '%') ORDER BY display_value' at line 1' in /home/asdf/index-ajax.php:61
Stack trace:
#0 /home/asdf/index-ajax.php(61): PDOStatement->execute(Array)
#1 {main}
  thrown in /home/asdf/index-ajax.php on line 61

Here's my code:

$qry = $CFG["DBH"]->prepare("SELECT DISTINCT CONCAT( city,  ', ', prov_stat,  ', ', country ) AS display_value FROM `contact` AND city LIKE CONCAT('%', :contactCity, '%') ORDER BY display_value;");
$qry->execute(array(':contactCity' => "van"));

I've tried finding references that talk about this message, why it's happening and what to do about it but it seems very common and nothing I've been able to read yet has contained a magic bullet. Can anyone see the problem in my code?

It's been a while since I've written SQL, but something seems off with your column list:

$qry = $CFG["DBH"]->prepare("SELECT DISTINCT CONCAT( city,  ', ', prov_stat,  ', ', country ) AS display_value FROM `contact` AND city LIKE CONCAT('%', :contactCity, '%') ORDER BY display_value;");
$qry->execute(array(':contactCity' => "van"));

I don't think you can join two columns together with AND , and especially not after you've selected the table. Additionally, you can't filter your query ( WHERE ) directly in the SELECT , as far as I know.

Something like this might work:

$qry = $CFG["DBH"]->prepare(
    "SELECT DISTINCT
        CONCAT( city,  ', ', prov_stat,  ', ', country ) AS display_value,
        city
     FROM `contact`
     WHERE city LIKE CONCAT('%', :contactCity, '%')
     ORDER BY display_value;"
);

$qry->execute(array(':contactCity' => "van"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM