$hostname="localhost"; //定義串連到的mysql伺服器名
$username="root"; //定義用於串連的使用者名稱
$password=""; //定義用於串連的密碼
$link=mysql_connect($hostname,$username,$password); //串連到本地mysql伺服器
if($link) //如果成功串連
{
echo "成功串連"; //輸出內容
}
else //如果串連失敗
{
echo "串連失敗"; //輸出內容
}
//mysql_close($link) //關閉已經開啟的mysql串連
//mysql_pconnect串連mysql資料庫
$link=mysql_pconnect($hostname,$username,$password); //開啟持久性串連
if(!$link) //如果不能串連
{
die('不能串連'.mysql_error()); //輸出資訊
exit(); //結束所有php操作
}
echo '持續串連成功';
/*
下面看軟串連查詢資料庫內容
*/
$link=mysql_connect($hostname,$username,$password)or die("could not connect:".mysql_error());
//轉換編碼以支援中文
mysql_query('set names gb2312;');
//選擇操作庫test
mysql_select_db("test")or die("could not select database:".mysql_error());
//執行sql查詢,從表中選擇名字
$query="select name from friends";
$result=mysql_query($query)or die("query failed:".mysql_error());
//匹配結果集到行迴圈輸出內容
for($i=mysql_num_rows($result)-1;$i>=0;$i--)
{
//移動內部結果的指標,如果沒有結果則輸內容
if(!mysql_data_seek($result,$i))
{
echo "cannot seek to row $i:".mysql_error()."n";
continue;
}
//從查詢結果取得一行作為對象
if(!($row=mysql_fetch_object($result)))
continue;
//輸出結果內容
echo "$row->name<br/>n";
}
//釋放結果集
mysql_free_result($result);
/*
其它操作
$escaped_item=mysql_escape_string($str); //將字串轉義
printf("escaped string:%sn",$escaped_item); //輸出轉義後的結果
$mydb=mysql_list_dbs($link); //列出資料庫
while($result=mysql_fetch_object($mydb)) //通過迴圈遍曆結果集並賦值給對象
{
echo $result->database."n"; //輸出對象內容
echo "<br>";
}