1. 程式人生 > >資料庫操作(程式碼)

資料庫操作(程式碼)

總結常見PHP連線MYSQL資料庫以及讀取寫入資料庫的方法

1、資料庫連線所涉及的值定義變為變數;

$mysql_server_name = 'localhost';  //MySQL資料庫伺服器

$mysql_username  = 'root';             //MySQL資料庫使用者名稱

$mysql_password = '123456';        //mysql資料庫密碼

$mysql_database = 'mydb';            //mysql資料庫名

可將上面的內容放在一個檔案中,隨時讓其他檔案呼叫。

舉例:內容放在db_config.php,需要用到資料庫的頁面可使用呼叫程式碼(require(“db_config.php”);)進行呼叫。

2、連線資料庫

$con = mysql_connect($mysql_server_name,$mysql_username,$mysql_password) 

or die("error connect");      //連線資料庫

mysql_query("set names utf8");         //資料庫輸出編碼,應該與資料庫編碼保持一致

mysql_select_db($mysql_database);        //開啟資料庫

$sql  = "select * from news";       //SQL語句

$result = mysql_query($sql,$con);      //查詢

3、讀取表中的內容,根據具體情況自己讀取,這裡使用while舉例

while ($row  = mysql_fetch_array($result)){

echo  "<div style = \"height = 24px; line-height = 24px; font-weight=bold\">";     //排版程式碼

echo  $row['topic']."<br/>";

echo  "</div>";     //編排程式碼

}

4、PHP寫入資料庫,MySQL資料的寫入

$con = mysql_connect($mysql_server_name,$mysql_username,$mysql_password);          //連線資料庫

mysql_query("set names 'utf8');        //資料庫輸出編碼

mysql_select_db($mysql_db);         //開啟資料庫

$sql  = "insert into messageboard (Topic,Content,Date) values ('$Topic','$Content','2016-8-23');

mysql_query($sql);

mysql_close();        //關閉MySQL資料庫