第四週-MySql與PHP結合-查詢範例 一、SELECT 1. AS 的應用 SELECT depart_clASs AS 班級,student_no AS 學號,student_name AS 姓名, address AS 地址 FROM stmd; select depart_clASs AS 班級,student_no AS 學號,student_name AS 姓名, address AS 地址 FROM stmd ORDER BY 學號; 2. LIKE 的應用 萬用字元 % 表匹配全部 _ 表匹配一個字元 SELECT * FROM stmd WHERE student_no LIKE "100%"; SELECT * FROM stmd WHERE student_name LIKE "林%";
作業:使用 LIKE 並以 AS 賦予中文標題 班級代碼的意義如下 第一碼 1:台北校區 2:新竹校區 第二三碼 64:日四技 54:夜四技 第四碼 D:資管系 E:資工系 第五碼 年級 第六碼 1:甲班 2:乙班 3:丙班
1. 查詢班級不是 "164D21" 的所有紀錄 2. 查詢班級不是 "164D21" 的所有紀錄按班級、學號由小到大 3. 查詢學號不是 "10014D001" 的所有紀錄,按學號、班級由小到大 4. 查詢班級是"164D21",學號不是 "10014D001" 的所有紀錄,按學號、班級由小到大 5. 查詢班級是 "164D2"的所有紀錄 6. 查詢班級有 D 的所有紀錄 7. 查詢姓 陳 的所有紀錄,按姓名由小到大 8. 查詢姓名中有 德 的所有紀錄,按學號由大到小 9. 查詢學號中有 D 的所有紀錄,按學號由小到大 10. 查詢學號中有 D 且姓 陳 的所有紀錄,按學號由小到大 11. 查詢台北校區的所有學生,按學號由小到大 12. 查詢新竹校區日四技的所有學生,按學號由小到大 13. 查詢台北校區日四技住台北市的所有學生,按學號由小到大 14. 查詢台北校區日四技不住台北市的所有學生,按學號由小到大 15. 查詢台北校區日四技一年級住台北市的所有學生,按學號由小到大 16. 查詢台北校區日四技一年級甲班住台北市的所有學生,按學號由小到大
二、MySQL與PHP的結合
1. config.php 儲存為utf8 儲存在 www下 <?php $host = "localhost"; // 本機 $user = "root"; // username $pwd = "1234"; // password $dbname="mydb"; // 資料庫名稱 $conn=mysql_connect($host,$user,$pwd) or die(mysql_error()); // 連接資料庫 mysql_query('SET NAMES utf8'); // 查詢結果utf8 mysql_select_db($dbname,$conn) or die(mysql_error()); //使用資料庫 ?>
2. style.css 儲存為utf8 儲存在 www下 <style type='text/css'> body { width:100%; margin:0 padding:0; font-family:'標楷體'; } table { border-collapse:collapse; border:1px solid black; empty-cells:show; width:100%; } th { background-color:'#ccccff'; border: 1px solid;} td { border: 1px solid; text-align : center; } p {background-color: 00FF00; display:inline;} .alt1 { background-color:'#ccccff'; font-weight:bold; } .alt2 { background-color:'#add8e6'; } .alt3 { background-color:'#fff8c6'; } </style>
3. search_stmd.php 儲存為utf8 儲存在 www下 <?php include "config.php"; $command=$_POST["command"]; if ($command=="") { echo "<html><head><title>MySql與PHP結合-查詢範例</title> <link rel='stylesheet' type='text/css' href='style.css'> </head><body><center> <form method='post' action=''> <table><tr><td class='alt1'>學號</td> <td><input type='text' name='student_no' size='9'></td> <td class='alt1'><input type='submit' name='command' value='查詢'></td></tr> </table></form></center></body></html>"; } if ($command=="查詢") { $student_no=trim($_POST["student_no"]); // 以學號為鍵值查詢 if ($student_no=="") $student_no="%"; // 查詢全部 $sql="select * from stmd where student_no like '$student_no' order by student_no"; $result=mysql_query($sql,$conn); // SQL命令執行 echo "<html><head><title>MySql與PHP結合-查詢範例</title> <link rel='stylesheet' type='text/css' href='style.css'> </head><body><center> <table><tr class='alt1'><td>班級</td><td>學號</td></tr>"; while ($myrow=mysql_fetch_array($result)) { // 取出一列 $depart_class=$myrow["depart_class"]; // 取出欄位 $student_no=$myrow["student_no"]; // 取出欄位 echo "<tr class='alt2'><td>$depart_class</td><td>$student_no</td></tr>"; } echo "</table></center></body></html>"; }
mysql_close($conn);
?>