'How to use mysql reserved keywords as column in where statement?

MYSQL won't let queries select rows when the column name is a mysql keyword in the where statement.

I'm creating a php api where it grabs a username that is attached to a key provided by the user but when it's grabbing the username it can't search for it using key == '$key' because "key" is a reserved MySQL word that the frontend generates (and it can't be changed.)

I've tried surrounding the column name in "s, 's, `s, and []s, none of which have worked. If anyone could help me that would be great.

$key = $_GET['key'];

$sql = "SELECT * FROM discordlink WHERE key = '$key'";
$result = $conn->query($sql);

It should be able to find the row attached to the key using the where clause provided but it doesn't becuase it's a mysql reserved keyword.



Solution 1:[1]

You can surround the column name with backticks(`) for the reserved mysql words

SELECT `key` FROM `table`

Solution 2:[2]

Bit late answer, but still there was no accepted answer I am adding this answer.

We can give alias name for table and refer reserved keyword column in WHERE statement i.e

SELECT * FROM discordlink AS d WHERE d.key = '$key'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rosy_acube
Solution 2 avatar