Reputation: 13
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
I want to filter them by genre 1 only so here is my code
<?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();
?>
But every time I want to filter them I need to change my where statment value, How can I do it dynamically?
Upvotes: 0
Views: 102
Reputation: 133400
assuming you can set the value for filter in a var name $myActID because you obtain this form a POST value enter by user
$myActID = $_POST['my_id'];
you could use a prepared statements and bind the value for filter
$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]);
you can accessing the result iterating over eg: using fetch
while ($row = $stmt->fetch()) {
print_r($row);
}
Upvotes: 1
Reputation: 3030
As I understand you want to make the genere_id of where as a variable so here is the sql statement
$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";
Upvotes: 0
Reputation: 2302
Try this instead, use a prepared statement then set $id to the id you want instead of modifying the query each time
<?php
include "mysql-connect.php";
$id = 1;
$sql = "SELECT title
FROM book
INNER JOIN list ON book.book_id = list.book_id
WHERE list.genre_id = ?
ORDER BY title ASC";
$stmt = $conn->prepare($query)
if($stmt){
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->bind_result($title);
$stmt->store_result;
$rows = $stmt->num_rows;
if($rows > 0){
while($stmt->fetch()){
echo $title;
}
}
$stmt->close();
}
$conn->close();
Upvotes: 1