简体   繁体   中英

SQL Query Syntax when adding extra condition check

I'm trying to write a SQL query that fetches an id and date. I am having some troubles getting the syntax correct:

$query = $this->pdo->prepare('SELECT * FROM `' . $this->table . '` WHERE `id` = ' . $id . ' AND `date` = ' . $date . '');

I originally had this without the second check against the date and it worked fine:

$query = $this->pdo->prepare('SELECT * FROM `' . $this->table . '` WHERE `id` = ' . $id . '');

but when I add the check for the date things go wrong.

Please help me locate the syntax error. Thank you!

UPDATE:

tried this with no luck still:

$query = $this->pdo->prepare('SELECT * FROM `' . $this->table . '` WHERE `id` = `' . $id. '` AND `date` = `' . $date . '` ');

As others have commented above, you didn't have quotes around your date. Your syntax would create this SQL:

... WHERE `id` = 123 AND `date` = 2018-06-12 -- WRONG

But correct syntax is as follows. In other words, a date constant should be delimited by single-quotes.

... WHERE `id` = 123 AND `date` = '2018-06-12' -- RIGHT

Your second try with back-ticks is also wrong. The back-ticks are for delimited identifiers like column names or table names. This syntax would mean that you're comparing id to a column whose name is 123 , and I assume you don't have such a column. Same for the back-ticks around the date—it's interpreted as a column named 2018-06-12 which is unlikely. MySQL does not treat back-ticks the same as single-quotes.

... WHERE `id` = `123` AND `date` = `2018-06-12` -- WRONG

However, there's a much easier solution. You won't have to worry about quotes if you use query parameters:

$sql = "SELECT * FROM `{$this->table}` WHERE `id` = ? AND `date` = ?";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([$id, $date]);

You're already using prepare() , so you should use it to its best advantage and use query parameters (the ? placeholders) instead of interpolating variables into your SQL query string.

You don't need quotes around strings or dates when you use parameters. In fact, you must NOT use quotes to delimit the ? parameter placeholders.

Notice I also show the PHP syntax for putting a variable directly into a string without breaking the string and using . for concatenation. You can do this if your PHP string is delimited with double-quotes. Read http://php.net/manual/en/language.types.string.php#language.types.string.parsing for details.

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