PHP Programing language

PHP MySQL JOIN
Previous Home Next

In MySQL database the data is inserted into the one table at a time. This is fine for simple tasks, but in the most real world MySQL usage you will often need to get data from multiple tables in a single query.

The Join condition follow in the table or a database for joining into a two or more tables into a single table. and after joining a two table in MySQL database and after created a single table .and you learning for created a joined table.

What is MySQL Join Table Setup

In this database We like to show examples and code before we explain anything in detail, and after so here is how you would combine two tables into one using MySQL. The two tables we will be using relate to a families eating habits.

Family Table

Position Age
Dad 45
Mom 41
Daughter 17
Dog

Food Table

Meal Position
Steak Dad
Salad Mom
Spinach Daughter
Tacos Dad

In this table's there ar two table , then you can join these tables and created a new single table. the family table and food table are attach together.

 

MySQL Join Simple Example

In this table Let's imagine that we wanted to SELECT all the dishes that were liked by a family member. this is a situation when we need to use the WHERE clause. We want to SELECT all the dishes WHERE a family member likes it.

We will be performing a generic join of these two tables using the Position column from each table as the connector.

Note: This example assumes you have created the MySQL tables "food" and "family". If you do not have either of them created, you can either create them using our MySQL Create Table lesson or do it manually yourself.

PHP and MySQL Code:

<?php

// Make a MySQL Connection
// Construct our join query

$query = "SELECT family.Position, food.Meal ".
"FROM family, food ".
"WHERE family.Position = food.Position";
	 
$result = mysql_query($query) or die(mysql_error());

// Print out the contents of each row into a table 

while($row = mysql_fetch_array($result))
	{
echo $row['Position']. " - ". $row['Meal'];
echo "<br />";
    }
?>

The statement "WHERE family.Position = food.Position" will restrict the results to the rows where the Position exists in both the "family" and "food" tables.

Output

Dad - Steak
Mom - Salad
Dad - Tacos

Those are the results of our PHP script. Let's analyze the tables to make sure we agree with these results.

Compare the Tables:

Family Table

Position Age
Dad 45
Mom 41
Daughter 17
Dog

Food Table

Meal Position
Steak Dad
Salad Mom
Spinach Daughter
Tacos Dad

Our results show that there were three meals that were liked by family members. And by manually perusing the tables it looks like there were indeed three meals liked by family members.

Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: