We’ll focus on PHP Prepared Statements, Secure MySQL Join Queries, Prevent SQL Injection, and PHP MySQL Example as primary keywords. These keywords have good search potential.
In this article, we’ll provide a real-world example of fetching related data from multiple tables. We will use JOIN and prepared statements in PHP.
PHP MySQL Join Queries Prepared Statement
$review_id = 1;
$user_id = 1;
$stmt = $connect->prepare("
SELECT n.id AS notification_id, n.reply_at, r.comment, r.rating,
p.product_image, u.name AS username
FROM tbl_notification n
JOIN tbl_reviews r ON n.review_id = r.review_id
JOIN tbl_product p ON r.product_id = p.product_id
JOIN tbl_user u ON n.user_id = u.id
WHERE n.review_id = ? AND n.user_id = ?
");
$stmt->bind_param("ii", $review_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
print_r($row);
}
Step-by-Step Explanation for beginners:
For Beginners who are learning the development, description is made.Then they will understand what is going on Step by Step.
1. Define Variables
$review_id = 1;
$user_id = 1;
These variables store the demo IDs for the review and user. You can add GET /POST method for fetching IDs
2. Create a Prepared Statement
$stmt = $connect->prepare("
SELECT n.id AS notification_id, n.reply_at, r.comment, r.rating,
p.product_image, u.name AS username
FROM tbl_notification n
JOIN tbl_reviews r ON n.review_id = r.review_id
JOIN tbl_product p ON r.product_id = p.product_id
JOIN tbl_user u ON n.user_id = u.id
WHERE n.review_id = ? AND n.user_id = ?");
The ? placeholders make the query safe from SQL Injections.
3. Bind Parameters
$stmt->bind_param("ii", $review_id, $user_id);
The “ii” means two integers are being bound to the query. If you find with string key then you can use
$stmt->bind_param('si', $stringKey, $user_id);
4. Execute the Query
$stmt->execute();
5. Fetch the Results and Print
while ($row = $result->fetch_assoc()) {
print_r($row);
}