PHP自學教程之MySQL資料庫

沉默術士發表於2017-07-03
 PHP訪問MySQL資料庫的一般步驟:
  1、連線MySQL資料庫:使用mysql_connect()函式建立與MySQL伺服器的連線。
  2、選擇MySQL資料庫:使用mysql_select_db()函式選擇MySQL資料庫伺服器上對於的資料庫。
  3、執行SQL語句:在選擇的資料庫中使用mysql_query()函式執行SQL語句。
  4、關閉結果集:資料庫操作完畢後,通過mysql_free_result()函式,釋放MySQL系統資源。
  5、關閉MySQL伺服器:在完成資料庫操作,應該使用mysql_close()函式關閉與資料庫伺服器連線。
  PHP連線MySQL資料庫例項程式碼:
<?php
//定義連線資料庫相關變數
$dbhost =”localhost” ;
$dbuser = “swxm”; // 我的使用者名稱
$dbpass = “swxm”; // 我的密碼
$dbname = “shopping”; // 我的mysql庫名
//連線到資料庫函式—mysql_connect
$connection=mysql_connect($dbhost,$dbuser,$dbpass);
if(!$connection){
die(“無法連線到MySQL資料庫:</br>”.mysql_error());//診斷連線錯誤
}
//選擇資料庫函式——–mysql_select_db
$db_selecct=mysql_select_db($dbname, $connection);
if(!$db_selecct)
{
die(“無法連線到指定的資料庫</br>”.mysql_error());
}
$query=”select * from  user “;//構建查詢語句
//執行SQL查詢函式———–mysql_query
$result=mysql_query($query);
if(!$result)
{
die(“無法進行相關查詢操作</br>”.mysql_error());
}
//查詢結果
while($result_row=mysql_fetch_row($result))//取出結果並顯示
{
$num=$result_row[0];
$age=$result_row[1];
$name=$result_row[2];
echo “<tr>”;
echo “<td>$num</td><br/>”;
echo “<td>$age</td><br/>”;
echo “<td>$name</td>”;
echo “</tr>”;
}
?>
  結果展示:


最新內容請見作者的GitHub頁:http://qaseven.github.io/


相關文章