PHP 和 SQL 解析单引号

PHP and SQL parsing single quotes

我在这里做了一些搜索,但没有找到我要找的东西。

我有一个表格需要填写,提交后将其添加到 SQL 数据库(使用 PHP)。但是,如果有人输入撇号或单引号,它就会爆炸......我需要能够解析每个文本字段以检查单引号以将其转义或找到其他方法来实现这一点。这是我的 SQL 声明...如果有帮助的话。

$query = "INSERT INTO workshopinfo (Year, Presentername, email, bio, arrival, title, description, costyn, matcost, schedlimit, additionalinfo, typeofws, verified)" .
"VALUES ('$year', '$presentername', '$email', '$bio', '$arrival', '$title', '$description', '$costyn', '$matcost', '$schedlimit', '$additionalinfo', '$typeofws', '$verified')";

当然,单引号会把它炸毁,双引号也会……每次都失败。可能有一个简单的解决方案。

我可能是发帖后才发现的。 php 函数 addslashes() 在这种情况下有效。

您可以将 PDO 与准备好的语句一起使用来处理 SQL 请求中的引号:

$req = $bdd->prepare("INSERT INTO yourTable (a, b, c) VALUES (:a, :myb, :c)");
$req->bindParam("a", $name, PDO::PARAM_STR); // string
$req->bindParam("myb", $title, PDO::PARAM_STR); // string 
$req->bindParam("c", $identifier, PDO::PARAM_INT); // integer
$req->execute();

有了这个,你就可以避免所有 SQL 注入。

文档:http://php.net/manual/en/book.pdo.php