PHP4与MySQL数据库操作函数详解(一)
来源:互联网 发布:数码暴龙网络侦探v字头 编辑:程序博客网 时间:2024/05/21 18:32
说PHP就不能不提MySQL,而要讲MySQL,那么PHP也是必然要被提起。PHP的迅速崛起,离不开MySQL,而MySQL的广泛应用,也与PHP休戚相关。
下面详细分析PHP4中与MySQL相关操作的函数(共32个,开头都为MySQL_):
<1>. 连接数据库服务器(database server)的函数(2个):
(1).MySQL_connect()
格式:int MySQL_connect(string [hostname] [:port],string [username],string [password]);
参数中的port参数表示数据库服务器的端口号,一般用它的默认端口号就可以了。
如果不填任何参数,则默认的hostname为localhost,username为root,password为空。
函数执行成功,返回一个int 类型的连接号(link_identifier),执行失败,返回false值。
例子:
<?PHP
$connect = MySQL_connect("localhost","user","password");
if($connect) echo "Connect Successed!"; //连接成功,显示Connect Successed!
else echo "Connect Failed!"; //连接失败,显示Connect Failed!
?>
在上例中,如MySQL_connect()执行失败,将显示系统的错误提示,而后继续往下执行。那,该如何屏蔽这些系统的错误提示并在失败后结束程序?
在MySQL中,允许在数据库函数之前加上@符号,屏蔽系统的错误提示,同时用die()函数给出更易理解的错误提示,然后die()函数将自动退出程序。
上例可以改为:
<?PHP
$connect = @MySQL_connect("localhost","user","password") or die ("Unable to connect database server!");
?>
如MySQL_connect()执行失败,将显示 Unable to connect database server!后,退出程序。
(2).MySQL_pconnect()
格式:int MySQL_pconnect(string [hostname] [:port],string [username],string [password]);
此函数与(1)的MySQL_connect()基本相同,区别在于:
--------- 当数据库操作结束之后 ,由(1)的MySQL_connect()建立的连接将自动关闭,而(2)的MySQL_pconnect()建立的连接将继续存在,是一种稳固持久的连接。
--------- 在(2)的MySQL_pconnect(),每次连接前,都会检查是否有使用同样的hostname,use,password的连接,如果有,则直接使用这个连接号。
--------- (1)的MySQL_connect()建立的连接可以用MySQL_close()关闭,而(2)的MySQL_pconnect()不能用MySQL_close()来关闭。
<2>.关闭数据库连接函数(1个):
MySQL_close()
格式:int MySQL_close(int link_identifier);
关闭由MySQL_connect()函数建立的连接,执行成功,返回ture值,失败则返回false值。
例子如下:
<?PHP
$connect = @MySQL_connect("hostname","user","password") or die("Unable to connect database server!");
$close = @MySQL_close($connect) or die ("Unable to close database server connect!");
?>
注:MySQL_close()不能关闭由MySQL_pconnect()函数建立的连接。
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>