| 2010/04/22 演練題目1. 建立資料庫 CREATE DATABASE mydb; 2 使用資料庫 USE mydb; 3. 建立資料表 CREATE TABLE stmd ( depart_class char(6), -- 班級代碼 student_no char(9), -- 學號 student_name char(10), -- 姓名 birth_date date, primary key(student_no) ); 4. 新增至資料表 INSERT INTO stmd VALUES("164D31","9614D001","張三","1986/01/01"); 5. 查詢全部資料 SELECT * FROM stmd; 6. 以PHP連接MySQL <?php $host = "localhost"; // 本機 $mysqlusername = "root"; // username $mysqlpwd = "1234"; // password $dbname="mydb"; // 資料庫名稱 $conn=mysql_connect($host,$mysqlusername,$mysqlpwd) or die(mysql_error()); // 連接資料庫 mysql_select_db($dbname,$conn) or die(mysql_error()); //使用資料庫 ?> 7. <?php include "config.php"; $command=$_POST["command"]; if ($command==null) { echo(" <html> <title>MySql 新增範例</title> <center> <form method='post' action=$PHP_SELF> <table border=0> <tr> <td>學號:</td> <td> <input type='text' name='student_no' size='9'> </td> </tr> </table> <input type='submit' name='command' value='新增'> <input type='reset' name='command' value='清除 '> </form> </center> </html> "); } if ($command=="新增") { $depart_class=$_POST["depart_class"]; // 取得班級 $student_no=$_POST["student_no"]; // 取得學號 $student_name=$_POST["student_name"]; // 取得姓名 $birth_date=$_POST["birth_date"]; // 取得出生日期 if ($student_no==null) { // 判斷是否有輸入 echo "<center>學號欄不能空白,請回前頁重新輸入</center><p>"; exit(); } // 準備 SQL Insert命令 $sql="insert into stmd values('$depart_class','$student_no','$student_name','$birth_date')"; $result=mysql_query($sql,$conn); // SQL 命令執行 $no_of_rows=mysql_affected_rows($conn); // 影響列數 if ($no_of_rows==1) // 新增成功一筆資料 echo("<html><center>新增成功</center></html>"); else echo mysql_error(); } ?> 8. 驗證插入是否成功 SELECT * FROM stmd; | |