Having trouble with output of using left and right join

I have two tables I use for a shipment tracking program using PHP. I have the need to display the contents of one table and a single field (status in shipinfo table) from a second table in a list (there is a common field in both tables (cookie) that I use to link the records).

The code below works great, except if there is no matching record in the second table (shipinfo), the cookie data is not displayed. In other words there will be no record in shipinfo, thus no cookie, if the order has not shipped. If there is a matching record in shipinfo, the cookie data is displayed.

Any ideas?


<?php

		include("db.php");
	
		// Get a connection to the database
		$con = @mysqli_connect($dbServer, $dbUser, $dbPass, $dbName);
		
		//SQL statement
		$sql = "SELECT * FROM orderinfo LEFT JOIN shipinfo ON orderinfo.cookie = shipinfo.cookie UNION SELECT * FROM orderinfo RIGHT JOIN shipinfo ON orderinfo.cookie = shipinfo.cookie ORDER BY oid DESC";
		
		// execute SQL query and get result
		$result = mysqli_query($con, $sql);

if ($result->num_rows > 0) {
    echo "<table><tr><th>Status</th><th>Order ID</th><th>Date</th><th>Sales</th><th>Company</th><th>Last Name</th><th>Cookie</th></tr>";
    // output data of each row
    while($row = mysqli_fetch_array($result, MYSQLI_ASSOC) ){
        echo "<tr><td>".$row["status"]."</td><td>".$row["oid"]."</td><td>".$row["date"]."</td><td>".$row["sales"]."</td><td>".$row["company"]."</td><td>".$row["lname"]."</td><td>".$row["cookie"]."</td></tr>";
    }
    echo "</table>";
    
} else {
    echo "0 results";
}
$con->close();
?>

Select the fields you actually need.

SELECT 
    si.status,
    oi.oid,
    oi.date,
    oi.sales,
    oi.company,
    oi.lname,
    oi.cookie
FROM 
    orderinfo oi 
LEFT JOIN 
    shipinfo si
        ON oi.cookie = si.cookie 
ORDER BY 
    oid 
DESC

Out of those columns, what comes from what tables?

1 Like

Thanks so much!! That did it.

Sponsor our Newsletter | Privacy Policy | Terms of Service