我正在尝试在内容表中插入值。如果我在VALUES内没有PHP变量,则效果很好。当我将变量$type
放在VALUES内时,此操作将无效。我在做什么错?
$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES($type, 'john', 'whatever')");
在任何MySQL语句中添加PHP变量的规则很简单:
因此,由于您的示例仅涉及数据文字,因此必须通过占位符(也称为参数)添加所有变量。为此:
这是所有流行的PHP数据库驱动程序的使用方法:
这样的驱动程序不存在。
mysqli
添加数据文字$type = 'testing';
$reporter = "John O'Hara";
$query = "INSERT INTO contents (type, reporter, description)
VALUES(?, ?, 'whatever')";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $type, $reporter);
$stmt->execute();
代码有点复杂,但是所有这些运算符的详细说明都可以在我的文章How to run an INSERT query using Mysqli中找到,并且可以大大简化此过程。
$type = 'testing';
$reporter = "John O'Hara";
$query = "INSERT INTO contents (type, reporter, description)
VALUES(?, ?, 'whatever')";
$stmt = $pdo->prepare($query);
$stmt->execute([$type, $reporter]);
在PDO中,我们可以将绑定部分和执行部分组合在一起,这非常方便。 PDO还支持命名占位符,有些占位符非常方便。
但是,有时我们添加了一个表示查询的另一部分的变量,例如关键字或标识符(数据库,表或字段名)。在这种情况下,必须对照脚本中写入的值列表[[explicitly来检查变量。这在我的另一篇文章Adding a field name in the ORDER BY clause based on the user's choice中进行了解释:[不幸的是,PDO没有标识符(表和字段名)的占位符,因此开发人员必须手动过滤掉它们。此类过滤器通常称为“白名单”(仅列出允许的值),而不是“黑名单”,其中列出不允许的值。
因此,我们必须在PHP代码中显式列出所有可能的变体,然后从中进行选择。
这里是一个例子:
$orderby = $_GET['orderby'] ?: "name"; // set the default value
$allowed = ["name","price","qty"]; // the white list of allowed field names
$key = array_search($orderby, $allowed, true); // see if we have such a name
if ($key === false) {
throw new InvalidArgumentException("Invalid field name");
}
方向应该使用完全相同的方法,
$direction = $_GET['direction'] ?: "ASC";
$allowed = ["ASC","DESC"];
$key = array_search($direction, $allowed, true);
if ($key === false) {
throw new InvalidArgumentException("Invalid ORDER BY direction");
}
经过这样的代码后,$direction
和$orderby
变量都可以安全地放入SQL查询中,因为它们等于允许的变体之一,否则将引发错误。
关于标识符的最后一件事,还必须根据特定的数据库语法设置它们的格式。对于MySQL,标识符周围应为backtick
个字符。因此,我们的订单示例的最终查询字符串将是
$query = "SELECT * FROM `table` ORDER BY `$orderby` $direction";
最好的选择是准备好的语句。