標籤:
在這裡我總結了常用的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.串連資料庫
$conn=mysql_connect($mysql_server_name,$mysql_username,$mysql_password) or die("error connecting") ; //串連資料庫 mysql_query("set names ‘utf8‘"); //資料庫輸出編碼 應該與你的資料庫編碼保持一致.南昌網站建設公司百恒網路PHP工程師建議用UTF-8 國際標準編碼. mysql_select_db($mysql_database); //開啟資料庫 $sql ="select * from news "; //SQL語句 $result = mysql_query($sql,$conn); //查詢
3.讀取表中的內容,這裡我們用while,可以根據具體情況,用for 或其他的。
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資料的寫入
$conn=mysql_connect($mysql_server_name,$mysql_username,$mysql_password); //串連資料庫 mysql_query("set names ‘utf8‘"); //資料庫輸出編碼 mysql_select_db($mysql_database); //開啟資料庫 $sql = "insert into messageboard (Topic,Content,Enabled,Date) values (‘$Topic‘,‘$Content‘,‘1‘,‘2011-01-12‘)"; mysql_query($sql); mysql_close(); //關閉MySQL串連
Php串連及讀取和寫入mysql資料庫的常用代碼