您可以使用带有*和ORDER BY的预准备语句吗?
因为我无法弄清楚如何去做。我现在已经尝试了一段时间。我已经看过其他一些线索,但还没有发现如何。如果没有,我怎么能得到像这样的mysqli查询并阻止sql注入?
欣赏任何想法或批评。
谢谢, 马特
<?php
require ($_SERVER['DOCUMENT_ROOT'].'/db-connect.php');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($stmt = $conn->prepare("SELECT * FROM websites ORDER BY ? DESC LIMIT 1")){
$id = 'id';
$stmt->bind_param('s',$id);
$stmt->execute();
$stmt->store_result();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['title'];
$stmt->free_result();
$stmt->close();
}
$conn->close();
?>
答案 0 :(得分:1)
您不能使用占位符作为列名。您需要对其进行硬编码:
$stmt = $conn->prepare("SELECT * FROM websites ORDER BY `id` DESC LIMIT 1");
或做类似的事情以允许用户输入:
switch ($_POST['sortby']) {
// Add all possible column names here
case 'id':
case 'col2':
case 'col3':
case 'col4':
case 'col5':
$sortby = $_POST['sortby'];
break;
default:
throw new Exception("Invalid sort by");
}
$stmt = $conn->prepare("SELECT * FROM websites ORDER BY `$sortby` DESC LIMIT 1");