0
$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.

4

2 回答 2

2

这就是 MySQL 语法的工作方式。PHP 只是为您构建查询。

PHP 将用 Loreum 替换 $string

所以 MySQL 查询看起来像这样

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

这是无效的语法。

因此需要加引号。

于 2013-08-11T11:55:57.683 回答
0

所有mysql字符串都应该用单引号

喜欢

               insert into table_name   (name,email)values('alok','alok@gmail.com');
于 2013-08-11T13:45:53.223 回答