Вы находитесь на странице: 1из 6

FetchDatafromMultipleTableswithPHPandMySQL

On12/19/2014ByPradeepKhodke

Thistutorialisabout,howtoJOINmorethanonetablesinPHPusingSQLjoinstatementandwithout
joinstatement,howtodisplayresultsfromMySQLdatabaseandshowtheminproperformat,Theactof
joiningtwoormoretablesinMySQLreferstocombinetwoormoretablesintoasingletable,let'stakea
look.

ConsiderFollowingTwoTables.
1:tbl_categories

CREATETABLEIFNOTEXISTS`tbl_categories`(
`cat_id`int(5)NOTNULLAUTO_INCREMENT,
`cat_name`varchar(20)NOTNULL,
PRIMARYKEY(`cat_id`)
)ENGINE=MyISAMDEFAULTCHARSET=latin1AUTO_INCREMENT=5;

Recordsforthistable:

INSERTINTO`tbl_categories`(`cat_id`,`cat_name`)VALUES
(1,'samsung'),
(2,'nokia'),
(3,'htc');

2:tbl_products

CREATETABLEIFNOTEXISTS`tbl_products`(
`product_id`int(5)NOTNULLAUTO_INCREMENT,
`product_name`varchar(30)NOTNULL,
`cat_id`int(5)NOTNULL,
PRIMARYKEY(`product_id`)
)ENGINE=MyISAMDEFAULTCHARSET=latin1AUTO_INCREMENT=7;

Recordsforthistable:

INSERTINTO`tbl_products`(`product_id`,`product_name`,`cat_id`)VALUES
(1,'galaxynote',1),
(3,'lumia530',2),
(5,'htcgrid',3);

Inabovetwotablesthereexistonecommoncolumn(field)named'cat_id'basedonwhichyoucan
establishrelatinshipbetweenthesetwotables.
Nowsupposeyouwanttoretrievedetailsfromproductstablealongwithproductcategory.
Youcandosousingthefollowingtwomethods.
1.ReferencingtwotablesinsingleSQLstatement.
2.UsingJOINstatements.

1.singlesqlstatement
Inordertoretrieveinformationfromfromtworelatedtablesyouneedtoreferencetwotablesinyour
SQLquery.
WithoutJoingeneralsyntax:

SELECTtbl_a.column1,tbl_a.column2
tbl_b.column1,tbl_b.column2
FROMtbl_a,tbl_b

WHEREtbl_a.commonfield=tbl_b.commonfield

intheabovesyntaxWHEREconditionestablishrelationbetweentablesbasedonthecommonfield.

Example.
index.php

<html>
<head>
<metahttpequiv="ContentType"content="text/html;charset=utf8"/>
<title>UsingsingleSQL</title>
<style>
table,td,th
{
padding:10px;
bordercollapse:collapse;
fontfamily:Georgia,"TimesNewRoman",Times,serif;
border:solid#ddd2px;
}
</style>
</head>
<body>
<tablealign="center"border="1"width="100%">
<tr>
<th>productid</th>
<th>productname</th>
<th>categoryname</th>
</tr>
<?php
mysql_connect("localhost","root");
mysql_select_db("dbtuts");
$res=mysql_query("SELECTc.*,p.*FROMtbl_categoriesc,tbl_productspWHEREc.cat_id=p.cat_id");
while($row=mysql_fetch_array($res))
{
?>

<tr>
<td><p><?phpecho$row['product_id'];?></p></td>
<td><p><?phpecho$row['product_name'];?></p></td>
<td><p><?phpecho$row['cat_name'];?></p></td>
</tr>
<?php
}
?>
</table>
</body>
</html>

InaboveexampleQueryusedasfollow:

SELECTc.*,p.*
FROMtbl_categoriesc,tbl_productsp
WHEREc.cat_id=p.cat_id

Queryexplained:
c=tbl_categories
p=tbl_products
*=fetchallrecordsfrombothtables.
1.candpisthealiasnameofthesetwotables.
2.Bothtableshouldhavecommoncolumn,firstisprimaryandsecondisforeignkey.
3.'cat_id'isprimarykeyincategoriestable.
4.'cat_id'isforeignkeyinproductstable.

Output:

2.usingjoin
InMySqlJOINsallowstheretrievalofdatarecordsfromoneormoretableshavingsamerelation
betweenthem,youcanalsouselogicaloperatortogetthedesiredoutputfromMySqljoinqueries.
1.InnerJOIN
itisadefaultjointype.
whentwotablesarejoinedusingINNERJOINoptionitreturnsonlythoserecordsfrombothtablesor
whichthereexistanentryforcommonfield.
example:

SELECTtbl_a.column1,tbl_a.column2
tbl_b.column1,tbl_b.column2
FROMtbl_aINNERJOINtbl_b
ONtbl_a.commonfield=tbl_b.commonfield

2.OuterJOIN
Syntax:

SELECTtbl_a.column1,tbl_a.column2
tbl_b.column1,tbl_b.column2
FROMtbl_aLEFTOUTERJOINtbl_b
ONtbl_a.commonfield=tbl_b.commonfield

that'sit...
Ihopethispostishelpfultoyou...
DownloadthisScriptfromthegivenlink.
DownloadScript

SelectDataWithPDO(+PreparedStatements)
Thefollowingexampleusespreparedstatements.
Itselectstheid,firstnameandlastnamecolumnsfromtheMyGueststableanddisplaysitinanHTML
table:
Example(PDO)
<?php
echo"<tablestyle='border:solid1pxblack;'>";
echo"<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

classTableRowsextendsRecursiveIteratorIterator{
function__construct($it){
parent::__construct($it,self::LEAVES_ONLY);
}

functioncurrent(){
return"<tdstyle='width:150px;border:1pxsolidblack;'>".parent::current()."</td>";
}

functionbeginChildren(){
echo"<tr>";
}

functionendChildren(){
echo"</tr>"."\n";
}
}

$servername="localhost";
$username="username";
$password="password";
$dbname="myDBPDO";

try{
$conn=newPDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$conn>setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt=$conn>prepare("SELECTid,firstname,lastnameFROMMyGuests");
$stmt>execute();

//settheresultingarraytoassociative
$result=$stmt>setFetchMode(PDO::FETCH_ASSOC);
foreach(newTableRows(newRecursiveArrayIterator($stmt>fetchAll()))as$k=>$v){
echo$v;
}
}
catch(PDOException$e){
echo"Error:".$e>getMessage();
}
$conn=null;
echo"</table>";
?>

Runexample
6

Вам также может понравиться