how to retrieve a single record from multiple tables in php

To retrieve a single record from multiple tables in PHP, we can use SQL JOIN statements to combine the data from different tables into a single result set. Here is an example code snippet to retrieve a single record from two tables using an inner join:

main.php
<?php
// database connection configuration
$host = "localhost";
$user = "username";
$password = "password";
$database = "my_database";
$conn = mysqli_connect($host, $user, $password, $database);

// fetch the record from the database
$query = "SELECT customers.name, orders.product_name, orders.order_date
          FROM customers
          INNER JOIN orders
          ON customers.id = orders.customer_id
          WHERE customers.id = 123";

$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);

// display the fetched data
echo "Customer Name: " . $row['name'] . "<br>";
echo "Product Name: " . $row['product_name'] . "<br>";
echo "Order Date: " . $row['order_date'] . "<br>";
?>
705 chars
24 lines

This code snippet fetches a single record from the "customers" and "orders" tables based on the customer ID value specified in the WHERE clause. It then displays the retrieved data on the web page. You can modify this code snippet to suit your own requirements, such as changing the table names, column names, or WHERE clause conditions.

related categories

gistlibby LogSnag