打印

[PHP教程] php4与mysql数据库操作函数详解(一)

php4与mysql数据库操作函数详解(一)


  说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()函数建立的连接。

   



TOP

返回顶部
AYBlue

Processed in 0.054056 second(s), 7 queries.

当前时区 GMT+8, 现在时间是 2009-1-8 12:08 京ICP备06054220号

清除 Cookies - 联系我们 - 163K.com - Archiver - WAP