book_id|title
1 |book 1
2 |book 2
3 |book 3
genre_id|name
1 |genre 1
2 |genre 2
id|book_id|genre_id
1 | 1 | 1
2 | 3 | 2
3 | 2 | 1
我只想按类型1过滤它们,所以这是我的代码
<?php
include "mysql-connect.php";
$sql = "SELECT title
FROM book
INNER JOIN list ON book.book_id = list.book_id
WHERE list.genre_id = 1
ORDER BY title ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "". $row["title"] ."<br>";
}
}
$conn->close();
?>
但是每次我要过滤它们时,都需要更改我的where陈述值,我该如何动态地执行它?
答案 0 :(得分:1)
假设您可以在$ myActID变量名中设置filter的值,因为您可以从用户输入的POST值中获取此表单
$myActID = $_POST['my_id'];
您可以使用准备好的语句并绑定过滤器的值
$stmt = $conn->prepare("SELECT title
FROM book
INNER JOIN list ON book.book_id = list.book_id
WHERE list.genre_id = ?
ORDER BY title AS");
$stmt->execute([$myActID]);
您可以访问迭代访问的结果,例如:使用
while ($row = $stmt->fetch()) {
print_r($row);
}
答案 1 :(得分:0)
据我了解,您希望将where的genere_id设置为变量,因此这是sql语句
$id=1;
$sql = "SELECT title
FROM book
INNER JOIN list ON book.book_id = list.book_id
WHERE list.genre_id =".$id."
ORDER BY title ASC";