【发布时间】:2013-09-26 08:20:06
【问题描述】:
我将如何编写一个 SQL 语句来插入可能包含撇号的值(例如,一个人的姓是 Conner,另一个人的姓是 O'Conner)?经过一番搜索,我找到了使用双撇号 (O''Conner example) 的示例,但每个示例都在INSERT 中硬编码了字符串。我没有遇到任何值可能包含或不包含撇号的示例。
我的简单语句在不使用撇号时没有任何问题,但如果使用撇号则失败。我知道我可以使用str_replace 替换撇号,但显然,这会导致 O'Conner 示例显示为 OConner。
这是一个简写版本,仅作为示例:
page1.php
// PHP
include_once('phpdata.php');
if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
// SQL connection
$insert = doInsert($firstname, $lastname);
// Execute statement using odbc_exec, etc.
}
// HTML
<input type="text" class="required" name="firstname" id="firstname" />
<input type="text" class="required" name="lastname" id="lastname" />
phpdata.php
function doInsert($firstname, $lastname) {
$insert = "INSERT INTO mytable (firstname, lastname)
VALUES ('$firstname', '$lastname')";
return $insert;
}
【问题讨论】:
-
考虑使用prepared statements。
-
我不小心遗漏了 INSERT 中最后一个封闭的引号,但是当我尝试编辑帖子时不断收到错误消息。不知道为什么我不能编辑它。
-
目前在 Stack Overflow 上可能有数百个这样的问题。 Here's a very popular one from the Related questions sidebar