防止使用like和%在大型sql select语句上注入

时间:2018-09-08 22:24:05

标签: php mysql phpmyadmin sql-injection

我有一个大型SQL查询,试图防止注入。 因为查询在变量上使用like和'%',所以我不知道如何格式化它以及我常用的

方法
$sql = "INSERT into UsedBook ( userId, bookId, price, description ) VALUES 
(?,?,?,?)";

if($stmt = mysqli_prepare($conn, $sql)){
    mysqli_stmt_bind_param($stmt, "iiis", $userId, $bookId, $price, 
$description);
mysqli_stmt_execute($stmt);
}

不适合该格式。

这是我的大查询。在底部附近寻找带有变量的like语句。

$sql = "SELECT DISTINCT Offering.offeringId, UsedBook.saleId, 
UsedBook.bookId, UsedBook.price,
UsedBook.timeStamp, Book.bookName, Classes.classNumber, Instructor.name,
Classes.departmentName, Offering.section, Users.email, UsedBook.description
FROM UsedBook, Book, Classes, Offering, Instructor, RequiredBook, Users
WHERE UsedBook.bookId = Book.bookId
and Classes.classId = RequiredBook.classId and Book.bookId = 
RequiredBook.bookId
and Classes.classId = Offering.classId and Offering.instructorId = 
Instructor.instructorId
and Offering.semesterId = $semester and UsedBook.userId = Users.userId and 
UsedBook.userId != $userId
and Classes.departmentName like '$departmentName%' and Classes.classNumber 
like '$classNumber%'
and Book.bookName like '$bookName%' and Offering.section like '$section%'";

1 个答案:

答案 0 :(得分:3)

您仍然可以使用准备好的语句,只需将%合并到绑定参数中,例如

$sql = "SELECT * FROM UsedBook WHERE bookName LIKE ?";
$param = "$bookName%";
if($stmt = mysqli_prepare($conn, $sql)){
    mysqli_stmt_bind_param($stmt, "s", $param);
    mysqli_stmt_execute($stmt);
}