PHP4 與 MySQL 數(shù)據(jù)庫操作函數(shù)詳解
2024-05-04 22:14:17
供稿:網(wǎng)友
說PHP就不能不提MySQL,而要講MySQL,那么PHP也是必然要被提起。PHP的迅速崛起,離不開MySQL,而MySQL的廣泛應(yīng)用,也與PHP休戚相關(guān)。
下面詳細(xì)分析PHP4中與MySQL相關(guān)操作的函數(shù)(共32個,開頭都為mysql_):
<1>. 連接數(shù)據(jù)庫服務(wù)器(database server)的函數(shù)(2個):
(1).mysql_connect()
格式:int mysql_connect(string [hostname] [ort],string [username],string [password]);
參數(shù)中的port參數(shù)表示數(shù)據(jù)庫服務(wù)器的端口號,一般用它的默認(rèn)端口號就可以了。
如果不填任何參數(shù),則默認(rèn)的hostname為localhost,username為root,password為空。
函數(shù)執(zhí)行成功,返回一個int 類型的連接號(link_identifier),執(zhí)行失敗,返回false值。
例子:
$connect = mysql_connect("localhost","user","password");
if($connect) echo "Connect Successed!"; //連接成功,顯示Connect Successed!
else echo "Connect Failed!"; //連接失敗,顯示Connect Failed!
?>
在上例中,如mysql_connect()執(zhí)行失敗,將顯示系統(tǒng)的錯誤提示,而后繼續(xù)往下執(zhí)行。那,該如何屏蔽這些系統(tǒng)的錯誤提示并在失敗后結(jié)束程序?
在MySQL中,允許在數(shù)據(jù)庫函數(shù)之前加上@符號,屏蔽系統(tǒng)的錯誤提示,同時用die()函數(shù)給出更易理解的錯誤提示,然后die()函數(shù)將自動退出程序。
上例可以改為:
$connect = @mysql_connect("localhost","user","password") or die ("Unable to connect database server!");
?>
如mysql_connect()執(zhí)行失敗,將顯示 Unable to connect database server!后,退出程序。
(2).mysql_pconnect()
格式:int mysql_pconnect(string [hostname] [ort],string [username],string [password]);
此函數(shù)與(1)的mysql_connect()基本相同,區(qū)別在于:
--------- 當(dāng)數(shù)據(jù)庫操作結(jié)束之后 ,由(1)的mysql_connect()建立的連接將自動關(guān)閉,而(2)的mysql_pconnect()建立的連接將繼續(xù)存在,是一種穩(wěn)固持久的連接。
--------- 在(2)的mysql_pconnect(),每次連接前,都會檢查是否有使用同樣的hostname,use,password的連接,如果有,則直接使用這個連接號。
--------- (1)的mysql_connect()建立的連接可以用mysql_close()關(guān)閉,而(2)的mysql_pconnect()不能用mysql_close()來關(guān)閉。
<2>.關(guān)閉數(shù)據(jù)庫連接函數(shù)(1個):
mysql_close()
格式:int mysql_close(int link_identifier);