为什么在将字符串变量插入mysql数据库php时需要添加引号 [英] Why we need to include quotation mark when inserting string variable to mysql database php

查看:343
本文介绍了为什么在将字符串变量插入mysql数据库php时需要添加引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这将产生一个错误:

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

但是当我更改为

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

推荐答案

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

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

PHP将用Loreum替换$ string

PHP will replace $string with the Loreum

因此MySQL查询将如下所示

so the MySQL query will look like this

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

这是无效的语法.

因此需要添加引号.

这篇关于为什么在将字符串变量插入mysql数据库php时需要添加引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆