Friday, June 8, 2012

left join mysql php

left join mysql php


Left Join  display of result is quite different with the simple join.For this tutorial fill your product table with 2 rows where product_id is not in customer table custom_id as bellow.



6& 7 Records product_id is not in customer_id of table customer.Now you can run the following php scripts and find the difference with simple join.

<?php
$host="localhost";
$username="root";
$password="";
$db_name="my_database";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql ="SELECT product.product_name, customer.customer_name FROM product
    LEFT JOIN  customer ON customer.product_id=product.product_id ";
     $result=mysql_query($sql);
?>
<table  align="center"  bgcolor="#15475c">
<tr bgcolor="#ddeef5">
<td align="center" ><strong>Product Name</strong></td>
<td align="center" "><strong>Customer Name</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr bgcolor="#d0e7f1">
<td><?php echo $rows['product_name']; ?></td>
<td><?php echo $rows['customer_name']; ?></td>
</tr>
<?php
}
?>
</table>

Resulting table is bellow

Product Name Customer Name
Win 2007 Jones
Photoshop Cs5 Harfer
Ilustrator cs5 Taylor
Maya 10 Lopez
3D Max 9 Bayker
Office 2007
Nero 10

Simple join product Names are displayed with the customer name only the customer has ordered the products. Here in Left Join all Product Names are displayed without considering ordered or not. 

Next

No comments:

Post a Comment