How can PHP efficiently retrieve information from a database table to determine who referred a specific customer?

To efficiently retrieve information from a database table to determine who referred a specific customer, you can use a SQL query to join the customer table with the referral table on the referral ID. This will allow you to fetch the information of the referring customer based on the referral ID of the specific customer.

<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query to retrieve referring customer information
$customer_id = 123; // ID of the specific customer
$sql = "SELECT referring_customer.name 
        FROM customer 
        JOIN referral ON customer.referral_id = referral.id 
        JOIN customer AS referring_customer ON referral.customer_id = referring_customer.id 
        WHERE customer.id = $customer_id";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of the referring customer
    while($row = $result->fetch_assoc()) {
        echo "Referring customer: " . $row["name"];
    }
} else {
    echo "No referring customer found for customer ID: $customer_id";
}

$conn->close();
?>