- 相關(guān)推薦
php連接mysql數(shù)據(jù)庫代碼
書山有路勤為徑,學(xué)海無涯苦作舟。學(xué)習(xí)PHP就要勤奮。下面是php連接mysql數(shù)據(jù)庫代碼,歡迎閱讀參考!
<?php
$mysql_server_name="localhost"; //數(shù)據(jù)庫服務(wù)器名稱$mysql_username="root"; // 連接數(shù)據(jù)庫用戶名$mysql_password="111111"; // 連接數(shù)據(jù)庫密碼$mysql_database="phptest"; // 數(shù)據(jù)庫的名字// 連接到數(shù)據(jù)庫$conn=mysql_connect($mysql_server_name, $mysql_username,$mysql_password);// 從表中提取信息的sql語句$strsql="select * from test";
// 執(zhí)行sql查詢
$result=mysql_db_query($mysql_database, $strsql, $conn);// 獲取查詢結(jié)果$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);
// 循環(huán)取出記錄
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);
// 關(guān)閉連接
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 "\t\t<td>$col_value</td>\n"; } print "\t</tr>\n"; } print "</table>\n";mysql_free_result($result);mysql_close($link);?>
-------------------------------------------------------------------------------------
代碼單獨(dú)存為一個(gè)文件conn.php,在以后要用到這些代碼時(shí)只要include這個(gè)頁面就可以了.如add.php這個(gè)頁面要要添加數(shù)據(jù)入數(shù)據(jù)庫,那么在add.php里include "conn.php";
【php連接mysql數(shù)據(jù)庫代碼】相關(guān)文章:
php入門之連接mysql數(shù)據(jù)庫05-04
PHP對數(shù)據(jù)庫MySQL的連接操作05-19
PHP腳本測試連接MySQL數(shù)據(jù)庫05-19
php向Mysql數(shù)據(jù)庫保存數(shù)據(jù)的代碼04-24
PHP向MySQL數(shù)據(jù)庫保存數(shù)據(jù)代碼03-21
如何在PHP中連接MySQL數(shù)據(jù)庫04-13
PHP與MYSql連接與查詢06-19