書山有路勤為徑,學海無涯苦作舟。學習PHP就要勤奮。下面是php連線mysql資料庫程式碼,歡迎閱讀參考! <?php $mysql_server_name="localhost"; //資料庫
服務器名稱$mysql_username="root"; // 連線資料庫使用者名稱$mysql_password="111111"; // 連線資料庫密碼$mysql_database="phptest"; // 資料庫的名字// 連線到資料庫$conn=mysql_connect($mysql_server_name, $mysql_username,$mysql_password);// 從表中提取資訊的sql語句$strsql="select * from test"; // 執行sql查詢 $result=mysql_db_query($mysql_database, $strsql, $conn);// 獲取查詢結果$row=mysql_fetch_row($result);echo '<font face="verdana">'; echo '<table border="1" cellpadding="1" cellspacing="2">';// 顯示欄位名稱echo "n<tr>n";for ($i=0; $i<mysql_num_fields($result); $i++){echo '<td bgcolor="#ff0F00"><b>'. mysql_field_name($result, $i); echo "</b></td>n"; } echo "</tr>n"; // 定位到第一條記錄 mysql_data_seek($result, 0); // 迴圈取出記錄 while ($row=mysql_fetch_row($result)) { echo "<tr>n"; for ($i=0; $i<mysql_num_fields($result); $i++ ){echo '<td bgcolor="#00FF00">';echo "$row[$i]"; echo '</td>'; } echo "</tr>n"; } echo "</table>n"; echo "</font>"; //
釋放資源 mysql_free_result($result); // 關閉連線 mysql_close(); ?> ------------------------------------------------------------------------------------- <?php$link = mysql_connect("mysql_host", "mysql_user", "mysql_password") or die("Could not connect");print "Connected successfully";mysql_select_db("my_database") or die("Could not select database");$query = "SELECT * FROM my_table";$result = mysql_query($query) or die("Query failed");print "<table>n";while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { print "t<tr>n"; foreach ($line as $col_value) { print "tt<td>$col_value</td>n"; } print "t</tr>n"; } print "</table>n";mysql_free_result($result);mysql_close($link);?> ------------------------------------------------------------------------------------- 程式碼單獨存為一個檔案,在以後要
用到這些程式碼時只要include這個頁面就可以了.如這個頁面要要新增資料入資料庫,那麼在裡include "";