हम दो तालिकाओं को जोड़ने के लिए MySQL JOIN के वाक्यविन्यास को PHP फ़ंक्शन - mysql_query() में उपयोग कर सकते हैं। यह फ़ंक्शन SQL कमांड को निष्पादित करने के लिए उपयोग किया जाता है और बाद में एक और PHP फ़ंक्शन - mysql_fetch_array() का उपयोग सभी चयनित डेटा को लाने के लिए किया जा सकता है।
इसे समझाने के लिए हम निम्न उदाहरण ले रहे हैं:
उदाहरण
इस उदाहरण में, हम दो MySQL तालिकाओं का उपयोग कर रहे हैं जिनमें निम्न डेटा है:
mysql> SELECT * FROM tcount_tbl; +-----------------+----------------+ | tutorial_author | tutorial_count | +-----------------+----------------+ | mahran | 20 | | mahnaz | NULL | | Jen | NULL | | Gill | 20 | | John Poul | 1 | | Sanjay | 1 | +-----------------+----------------+ 6 rows in set (0.01 sec) mysql> SELECT * from tutorials_tbl; +-------------+----------------+-----------------+-----------------+ | tutorial_id | tutorial_title | tutorial_author | submission_date | +-------------+----------------+-----------------+-----------------+ | 1 | Learn PHP | John Poul | 2007-05-24 | | 2 | Learn MySQL | Abdul S | 2007-05-24 | | 3 | JAVA Tutorial | Sanjay | 2007-05-06 | +-------------+----------------+-----------------+-----------------+ 3 rows in set (0.00 sec)
अब, निम्न PHP स्क्रिप्ट तालिकाओं को जोड़कर tutorials_tbl तालिका से सभी लेखकों का चयन करेगी और tcount_tbl से संबंधित ट्यूटोरियल की संख्या लेगी।
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
FROM tutorials_tbl a, tcount_tbl b
WHERE a.tutorial_author = b.tutorial_author';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "Author:{$row['tutorial_author']} <br> ".
"Count: {$row['tutorial_count']} <br> ".
"Tutorial ID: {$row['tutorial_id']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>