为什么我们需要在将字符串变量插入mysql数据库php时包含引号

$string = 'Loreum';
$insert = "INSERT INTO table (field1, field2 ) VALUES ($string , 7)";
$conn -> query($insert)

This will produce an error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ashfjksaf' in 'field list'' in C:\xampp\htdocs\yipee.php:23 Stack trace: #0 C:\xampp\htdocs\yipee.php(23): PDO->query('INSERT INTO yea...') #1 {main} thrown in C:\xampp\htdocs\yipee.php on line 23

However when I change to

$insert = "INSERT INTO table (field1, field2 ) VALUES ('$string' , 7)";

It works as expected.I wonder why we need to include single quotation mark in the string variable.I thought we only need to include quotation mark on literal string.

This is how the MySQL syntax works. PHP is merely constructing the query for you.

PHP will replace $string with the Loreum

so the MySQL query will look like this

INSERT INTO table (field1, field2 ) VALUES (Loreum , 7)

which is invalid syntax.

Therefore the quotation marks need to be added.

all mysql string should be in single quote

like

               insert into table_name   (name,email)values('alok','alok@gmail.com');