如何使用PHP编写的语句根据变量值设置ORDER BY列?

问题描述 投票:-1回答:1

我正在尝试允许用户根据他们选择的列值对配置文件进行排序。但这是行不通的。在此示例中,$_POST['column']的可能值为ageuser_since。如何将列值安全地插入字符串?

$sql="SELECT uid,coverphoto,profilepic,age,bio,user_since FROM profile WHERE status = ? ORDER BY ? DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $_POST['status'],$_POST['column']);
$stmt->execute();
$stmt->bind_result($uid,$coverphoto,$profilepic,$age,$bio,$user_since);
while($stmt->fetch()) {
//etc.. echo profile block
}
php mysql sql sql-order-by prepared-statement
1个回答
1
投票

您不能将列名作为参数传递给查询。这是因为数据库需要该信息来解析查询并准备其执行计划。

因此,您需要将列名称连接到查询字符串中。

$sql="SELECT uid,coverphoto,profilepic,age,bio,user_since FROM profile WHERE status = ? ORDER BY " . $_POST['column'] . " DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $_POST['status']);

这意味着您需要预先验证用户在应用程序中发布的值,例如使用预先定义的值列表。

© www.soinside.com 2019 - 2024. All rights reserved.