在網站後台,經常要與資料庫打交道。本文介紹如何使用XAMPP來管理MySql資料庫及如何用PHP來訪問MySql資料庫。
一.使用XAMPP來管理MySql資料庫
首先使用XAMPP開啟MySql的管理頁面。步驟如下:啟動XAMPP後點擊Admin進入XAMPP for Windows的首頁面,在首頁面中點擊phpMyAdmin。
進入phpMyAdmin頁面後,建立資料庫test並在此資料庫中建立t_student表,表共三個欄位,編號id,姓名name,年齡age。
然後就可以開始用PHP來訪問MySql資料庫了。由於PHP已經對訪問MySql資料庫作了良好的封裝,因此用PHP訪問MySql是一件非常容易的事情。
二.PHP訪問MySql資料庫
下面的PHP程式訪問test資料庫中t_student表,讀取資料並以表格的形式輸出資料。全部程式碼如下:
// by MoreWindows( http://blog.csdn.net/MoreWindows )//定義常量define(DB_HOST, 'localhost');define(DB_USER, 'root');define(DB_PASS, '111111');define(DB_DATABASENAME, 'test');define(DB_TABLENAME, 't_student');//資料庫表的列名$dbcolarray = array('id', 'name', 'age');//mysql_connect$conn = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("connect failed" . mysql_error());mysql_select_db(DB_DATABASENAME, $conn);//讀取表中紀錄條數$sql = sprintf("select count(*) from %s", DB_TABLENAME);$result = mysql_query($sql, $conn);if ($result){$count = mysql_fetch_row($result);}else{die("query failed");}echo "表中有$count[0] 條記錄<br />";$sql = sprintf("select %s from %s", implode(",",$dbcolarray), DB_TABLENAME);$result = mysql_query($sql, $conn);//表格echo '<table id="Table" border=1 cellpadding=10 cellspacing=2 bordercolor=#ffaaoo>'; //表頭$thstr = "<th>" . implode("</th><th>", $dbcolarray) . "</th>";echo $thstr;//表中的內容while ($row=mysql_fetch_array($result, MYSQL_ASSOC))//與$row=mysql_fetch_assoc($result)等價{echo "<tr>";$tdstr = "";foreach ($dbcolarray as $td)$tdstr .= "<td>$row[$td]</td>";echo $tdstr;echo "</tr>";}echo "</table>";mysql_free_result($result);mysql_close($conn);
運行結果如下:
這種HTML元素全由PHP輸出的方式比較原始,下一篇將介紹用smarty來完成讀取資料庫的任務並將《jquery 表格的增加刪除和修改及設定奇偶行顏色》中的設定表格奇偶行顏色的功能加入。
轉載請標明出處,原文地址:http://blog.csdn.net/morewindows/article/details/7086524