php連接mysql數據庫代碼
來源:文萃谷 3.07W
書山有路勤為徑,學海無涯苦作舟。學習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 "";