標籤:style blog http color 使用 os 資料 ar
PHP使用MySQL,從串連、建立、到結果顯示
1 <?php 2 //串連MySQL測試 3 $db = mysql_connect("localhost","root","wenwen"); 4 if (!$db) 5 { 6 die(‘Could not connect: ‘ . mysql_error()); 7 } 8 else 9 {10 echo "connect success!";11 }12 13 //建立資料庫14 if (!mysql_query("CREATE DATABASE my_db",$db))15 {16 echo "Error creating database: " . mysql_error();17 }18 19 //選擇資料庫20 mysql_select_db("my_db", $db);21 22 //建立表23 $sql = "CREATE TABLE Persons 24 (25 FirstName varchar(15),26 LastName varchar(15),27 Age int28 )";29 mysql_query($sql,$db);30 31 //插入資料32 mysql_query("INSERT INTO Persons (FirstName, LastName, Age) 33 VALUES (‘Jordan‘, ‘Michael‘, ‘51‘)");34 mysql_query("INSERT INTO Persons (FirstName, LastName, Age) 35 VALUES (‘Bryant‘, ‘Kobe‘, ‘36‘)");36 37 //建立結果集38 $sql = "SELECT * FROM Persons";39 $result = mysql_query($sql); 40 41 //在 HTML 表格中顯示結果42 echo "<table border=‘1‘>43 <tr>44 <th>FirstName</th>45 <th>LastName</th>46 <th>Age</th>47 </tr>";48 49 while($rs = mysql_fetch_array($result))50 {51 echo "<tr>";52 echo "<td>" . $rs[‘FirstName‘] . "</td>";53 echo "<td>" . $rs[‘LastName‘] . "</td>";54 echo "<td>" . $rs[‘Age‘] . "</td>";55 echo "</tr>";56 }57 echo "</table>";58 59 //關閉串連60 mysql_close($db);61 ?>
運行效果
DB中的變化