Lessen here we are going to discuss are joining of 2 tables and 3 tables using php scripts. This tutorial we need to have below 3 tables.
Simple join mysql php
CREATE TABLE IF NOT EXISTS `product` ( `product_id` int(11) NOT NULL AUTO_INCREMENT, `product_name` varchar(100) NOT NULL, PRIMARY KEY (`product_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; | |
CREATE TABLE IF NOT EXISTS `customer` ( `customer_id` int(11) NOT NULL AUTO_INCREMENT, `customer_name` varchar(100) NOT NULL, `product_id` int(11) NOT NULL, PRIMARY KEY (`customer_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; |
|
CREATE TABLE IF NOT EXISTS `orders` ( `id` int(11) NOT NULL AUTO_INCREMENT, `date` date NOT NULL, `customer_id` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; |
Now we will join the table product and customer to display product name from table product and customer name from table customer in a single table as below.
Product Name | Customer Name |
Photoshop Cs5 | Harfer |
Ilustrator cs5 | Taylor |
Win 2007 | Jones |
Maya 10 | Lopez |
3D Max 9 | Bayker |
<?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,customer WHERE product.product_id = customer.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> |
No comments:
Post a Comment