我不知道为什么下面的mysql查询一直失败。它告诉我它的语法无效。它总是在代码的em mail区域显示,但是没有明显的错误。在将字符串传递到mysql查询之前,我正在清理它们
$query = "INSERT INTO `ToReview` (`number`, `role`, `name`, `email`, `dob`,
`englishskills`, `previousmember`, `reasonYes`, `whyjoin`,
`whatcouldyoubring`, `roleplayexperience`, `roleplayexperiencedetail`,
`commit`, `minimumperiod`) VALUES (NULL, ".$role.", ".$name.", ".$email.",
".$dob.", ".$englishskills.", ".$previousmember.", ".$reasonYes.",
".$whyjoin.", ".$whatcouldyoubring.", ".$roleplayexperience.",
".$roleplayexperiencedetail.", ".$commit.", ".$minimumperiod.");";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
3条答案
按热度按时间aamkag611#
像这样的字符串
$name
需要使用'
.或者你可以用事先准备好的陈述
5w9g7ksd2#
您的查询不会在values子句中的每个值周围加任何单引号。除非它们都是数值或null,否则这将导致无效的sql。
你可以看到它如果你
echo $query
使用前:insert语句中的每个字符串或日期值都需要单引号。
您可以通过编写如下代码来解决此问题:
但我犯了个错误,忘了其中一个单引号。你能认出它吗?
如果您使用带参数的准备好的查询,并且停止将变量复制到sql字符串中,那么就容易多了。这样编写动态sql就更容易了,而不必费尽心思去寻找
这是一份事先准备好的声明
?
不需要任何报价。事实上,你不能在每一句话的前后加引号?
因为那会使它成为一个文字'?'
而不是占位符。然后准备查询,将变量绑定到其中。
您需要与占位符数量相同的变量,并以它们在查询中出现的相同顺序绑定它们。mysqli还需要一个类似
'sss...'
其中该字符串中的每个字母对应于一个参数,'s'表示该参数是字符串,'i'表示该参数是整数,等等。准备好并绑定参数后,只需执行prepared语句即可得到结果:
这样你就不会因为试图匹配所有不同类型的引号而让自己眼睛疲劳。
另一个提示:pdo使这更容易!只需将数组传递给execute函数,就可以在一个步骤中绑定和执行。
zazmityj3#
如果要在结尾分号处用双引号括起来,请将其删除,然后重试