ตัวอย่างการใช้โค๊ด join table [PHP/MySQL]
--โจทย์--
------------------------------------------------------------------------------------------------
- ให้เขียนโค้ด PHP กับ MySQL ออกรายงานเพื่อแสดงข้อมูลในรูปแบบตาราง ซึ่งเป็นข้อมูลลูกค้าทั้งหมด แล้วแสดงว่าลูกค้าดังกล่าวอยู่ประเทศอะไรด้วย (ดึงข้อมูลมาจากตาราง customer join กับ country)
------------------------------------------------------------------------------------------------
ขยายโจทย์
- อย่างแรกต้องมีฐานข้อมูลก่อนโดยอาจจะสร้างเองหรือใช้การ import เข้ามาจากด้านนอก
- อย่างที่ 2 โค๊ดที่ใช้ในการแสดงผล
ประกอบด้วยหลักๆ 2 หน้า คือ
1. หน้า connect กับฐานข้อมูล
ประกอบด้วยหลักๆ 2 หน้า คือ
1. หน้า connect กับฐานข้อมูล
2. หน้า โค๊ดหลัก
ตัวอย่าง หน้า connect กับฐานข้อมูล
<?
$host="localhost"; /*ชื่อโฮส*/
$username="root"; /*ชื่อผู้ใช้ของโฮส ปกติถ้าไม่ได้ใส่อะไรจะตั้งไว้ว่า root*/
$password="1234"; /*รหัสผ่านของโฮส ปกติถ้าไม่ได้ใส่อะไรจะตั้งไว้ว่า 1234*/
$db="mydatabase"; /*ชื่อฐานข้อมูลที่ต้องการเชื่อม*/
$connect= mysql_connect( $host,$username,$password) or die ("ไม่สามารถเชืื่อมต่อฐานข้อมูลได้");
mysql_db_query($dbname,"SET NAMES tis620"); /*คำสั่งเชื่อมต่อฐานข้อมูล*/
?>
ตัวอย่าง โค๊ดหลัก
<html>
<head>
<title>Customer</title>
</head>
<body>
<?
include("connect2.php"); /*คำสั่งดึงไฟล์การเชื่อมต่อในหน้า connect มาใช้*/
mysql_connect( $host,$username,$password) or die ("ไม่สามารถติดต่อกับฐานข้อมูลได้ ");
mysql_select_db($db) or die("ไม่พบฐานข้อมูล");
$sql="SELECT e.CustomerID, e.Name, e.Email, e.Used, e.Budget, d.CountryName
FROM customer e
JOIN country d ON e.CountryCode = d.CountryCode";
$db_query=mysql_db_query($db,$sql);
$num_rows=mysql_num_rows($db_query); /*คำสั่ง join table*/
?>
<table width="1000px" border="1" align="center"> /*หัวตาราง*/
<tr bgcolor="#FF0066">
<th>CustomerID</th>
<th>Name</th>
<th>Email</th>
<th>Country</th>
<th>Budget</th>
<th>Used</th>
</tr>
<?
$a=0;
while($a < $num_rows)
{
$result = mysql_fetch_array($db_query); /*แสดงค่าของข้อมูลในฐานข้อมูล*/
$a1=$result[CustomerID];
$a2=$result[Name];
$a3=$result[Email];
$a4=$result[CountryName];
$a5=$result[Budget];
$a6=$result[Used];
echo "<tr bgcolor='#99FF33'>" .
"<td align='center'>" . $a1. "</td>" .
"<td align='center'>" . $a2 . "</td>" .
"<td align='center'>" . $a3 . "</td>" .
"<td align='center'>" . $a4 . "</td>" .
"<td align='center'>" . $a5 . "</td>" .
"<td align='center'>" . $a6 . "</td>" .
"</tr>";
$a++;
}
mysql_close();
?>
</table>
</body>
</html>
ผลรัน