我有一些从MySQL数据库用PHP输出到页面上的图像。输出它们的while
循环包含一个连接,因为它从两个数据库表(一个imageposts
表和一个users
表)中获取数据。
使用当前输出运行查询,但由于没有用户输入,因此使用以下代码:
<?php
// IMAGE GRID JOIN
$stmt = $connection->query("SELECT imgp.*, u.id, u.firstname, u.lastname
FROM imageposts AS imgp
INNER JOIN users AS u ON imgp.user_id = u.id");
while ($row = $stmt->fetch()) {
// from imageposts table
$db_image_id = htmlspecialchars($row['image_id']);
$db_image_title = htmlspecialchars($row['image_title']);
$db_image_filename = htmlspecialchars($row['filename']);
$db_ext = htmlspecialchars($row['file_extension']);
$db_username = htmlspecialchars($row['username']);
// from users table
$db_firstname = htmlspecialchars($row['firstname']);
$db_lastname = htmlspecialchars($row['lastname']);
?>
-- HTML OUTPUT
<?php } ?>
我还为网站设置了我的第一个搜索表单,当图像输出时,我希望它们与上面相同的信息(除了搜索查询),但是因为它是一个搜索表单并且有用户输入,我将需要使用一个准备好的语句,我不知道如何处理这个问题?
搜索将在imageposts
表的image_title
列上进行,因此就sudo代码而言,它将是:
$searchSQL = "SELECT * FROM `imageposts` WHERE `image_title` LIKE %$searchQuery% ";
,其中$searchQuery
为搜索输入字段的值。
但是我如何将它与这个问题的第一部分中的查询集成,并且还使用准备好的语句来保证安全性?
MySQL会是这样吗?:
"SELECT imgp.*, u.id, u.firstname, u.lastname
FROM imageposts AS imgp
INNER JOIN users AS u ON imgp.user_id = u.id WHERE image_title LIKE %$searchQuery%"
如果是,我如何使它在$searchQuery
上的准备语句安全?
备选方案1:
$sql = "SELECT imgp.*, u.id, u.firstname, u.lastname
FROM imageposts AS imgp
INNER JOIN users AS u ON imgp.user_id = u.id
WHERE image_title LIKE CONCAT('%', ?, '%')";
$stmt = $connection->prepare($sql);
$stmt->execute([$searchQuery]);
替代2:
$sql = "SELECT imgp.*, u.id, u.firstname, u.lastname
FROM imageposts AS imgp
INNER JOIN users AS u ON imgp.user_id = u.id
WHERE image_title LIKE ?";
$stmt = $connection->prepare($sql);
$stmt->execute(["%{$searchQuery}%"]);