PHP新手上路(十一) 数据库链接
10.PHP最大的特色就是操作数据库的能力特别的强大,PHP提供对多种数据库的支持。
通过PHP你可以轻松的连接到数据库,请求数据并将其显示在你的web站点中,甚至修改数据库中的数据。在这一节里我们主要以在互联网上跟PHP一起使用得最多的MySQL数据库为例,介绍一下相关的MySQL数据库的操作函数以及数据库的基本操作等方面的知识。
在MySQL数据库中,我们用来连接数据库的函数有两个,它们分别为:integermysql_connect(stringhost,stringuser,stringpassword);integermysql_pconnect(stringhost,stringuser,stringpassword);mysql_connect函数和mysql_pconnect函数都是对指定主机上MySQL数据库的连接,如果该数据库位于一个不同的端口,则可以在主机名后加上冒号和端口号。函数的参数也可以缺省不填,如果不填参数,默认的主机名是“localhost”,用户名为数据库管理员,默认值为“root”,密码为空。与数据库连接成功之后,这两个函数都可以返回一个连接号,如果连接失败,则返回一个false值。让我们来看看下面几句语句:<?$db=mysql_connect("localhost","user","password");mysql_select_db("mydb",$db);?>注释:$db=mysql_connect("localhost","user","password");我们将mysql的链接参数,包括主机名、用户名和密码作为mysql_connect()的参数,同时得到返回值为$db,这样,在下面的语句中,我们就可以将变量$db作为一个连接mysql数据库的连接号来使用。mysql_select_db("mydb",$db);将PHP程序链接到mydb数据库中,这样程序与数据库的链接就完成了。
10.1一个简易的数据库留言簿
在完成数据库的链接之后,我们就可以对数据库进行一系列的操作。下面是一个简易的数据库留言簿程序(guestbook.php3):
我假设你机子上的MySQL数据库以及管理MYSQL数据库的工具Phpmyadmin_2.0.5都已经安装完成,并且可以正常工作。
我们要做的第一件事情是创建一个留言数据库,假定名字为:mydb。
1、启动浏览器,打开Phpmyadmin_2.0.5的管理WEB界面。
2、在“Createnewdatabase”文本框内输入数据库名称mydb,然后按create按键。
下一步,我们要在该留言数据库下创建一个数据表,假定名字为:guestbook。
创建该数据表的命令如下所示:
CREATETABLEguestbook(IDINTNOTNULLAUTO_INCREMENT,nameCHAR(250),emailCHAR(250),jobCHAR(250),commentsBLOB,PRIMARYKEY(ID));
最后,将下面的留言簿程序挎贝到你机子的可写目录下面,并保存成guestbook.php3文件。就这么简单,你已经有了自己的留言簿了。
10.2留言簿程序(guestbook.php3):
<?php /*$host:yourMySQL-host,usually'localhost'*//*$user:yourMYSQL-username*//*$password:yourMySQL-password*//*$database:yourMySQL-database*//*$table:yourMySQL-table*//*$page_title:thetitleofyourguestbook-pages*//*$admin_mail:email-addressoftheadministratortosendthenewentriesto*//*$admin_name:thenameoftheadministrator*//*$html_mail:sayyesifyourmail-agentcanhandleHTML-mail,elsesayno*/
$host="localhost";$user="";$password="";$database="mydb";$table="guestbook";$page_title="pertguestbook";$admin_mail="pert@21cn.com";$admin_name="Webmaster";$html_mail="no";
?><HTML><HEAD><TITLE><?phpecho$page_title;?></TITLE></HEAD><BODYBGCOLOR="#FFFFFF"LINK="#000000"><FONTFACE="Verdana"SIZE="-2"><?
/*connecttothedatabase*/mysql_pconnect("$host","$user","$password")ordie("Can'tconnecttotheSQL-server");mysql_select_db("$database");
/*action=view:retrievedatafromthedatabaseandshowittotheuser*/if($action=="view"){
/*functionforshowingthedata*/functionsearch_it($name){
/*somevars*/global$offset,$total,$lpp,$dir;global$table,$html_mail,$admin_name,$admin_mail;
/*selectthedatatogetoutofthedatabase*/$query="SELECTname,email,job,commentsFROM$table";$result=mysql_query($query);$total=mysql_numrows($result);
print"<CENTER><FONTFACE="Verdana"SIZE="-2"><AHREF="guestbook.php3?action=add"onMouseOver="window.status='Addyourname';returntrue"onMouseOut="window.status='';returntrue"TITLE="Addyourname">加入留言</A></FONT></CENTER><br><br>";
if($total==0){print"<CENTER>此刻没人留言</CENTER><br><br>";}
elseif($total>0){
/*default*/$counter=0;if($dir=="")$dir="Next";$lpp=5;if($offset==0)$offset=0;
if($dir=="Next"){
if($total>$lpp){
$counter=$offset;$offset+=$lpp;$num=$offset;
if($num>$total){$num=$total;}}
else{$num=$total;}}
elseif($dir=="Previous"){
if($total>$lpp){$offset-=$lpp;
if($offset<0){$offset=0;}
$counter=$offset-$lpp;
if($counter<0)$counter=0;$num=$counter+$lpp;}
else{$num=$total;}}
while($counter<$num){$j=0;$j=$counter+1;
/*nowreallygrabthedata*/$i1=mysql_result($result,$counter,"name");$i2=mysql_result($result,$counter,"email");$i3=mysql_result($result,$counter,"job");$i4=mysql_result($result,$counter,"comments");
$i4=stripslashes("$i4");
/*printitinanicelayout*/print"<CENTER>n";print"<TABLEWIDTH=400BORDER=0ALIGN=CENTERVALIGN=TOP><TR><TD><FONTFACE="Verdana"SIZE="-2">n";print"<HR>n";print"<BR><B>Name:</B>$i1n";print"<BR><B>email:</B><AHREF="mailto:$i2"onMouseOver="window.status='Email$i2';returntrue"onMouseOut="window.status='';returntrue"TITLE="Email$i2">$i2</A>n";print"<BR><B>Job:</B>$i3n";print"<BR><B>Comment:</B>n";print"<BR>$i4n";print"</FONT></TD></TR></TABLE>n";print"</CENTER>n";$counter++;}}mysql_close();}
/*executethefunction*/search_it($name);
/*SeeifweneedtoputontheNEXTorPREVIOUSbuttons*/if($total>$lpp){echo("<formaction="$PHP_script"method="POST">n");
/*SeeifweneedaPREVIOUSbutton*/if($offset>$lpp){echo("<inputtype="submit"value="Previous"name=dir>n");}
/*SeeifweneedaNEXTbutton*/if($offset<$total){echo("<inputtype="submit"value="Next"name=dir>n");}
echo("<inputtype=hiddenname="offset"value="$offset">n");echo("<inputtype=hiddenname="name"value="$name">n");echo("</form>");}}
/*action=add:showaformwheretheusercanenterdatatoaddtothedatabase*/elseif($action=="add"){?>
<TABLEWIDTH="460"ALIGN="CENTER"VALIGN="TOP"><THCOLSPAN="2"><P>请您填写留言</TH><FORMNAME="guestbook"ACTION="guestbook.php3?action=send"METHOD="POST"><TR><TDALIGN="RIGHT"VALIGN="TOP">您的大名:</TD><TD><INPUTTYPE=textNAME=name></TD></TR><TR><TDALIGN="RIGHT"VALIGN="TOP">您的E-mail:</TD><TD><INPUTTYPE=textNAME=email></TD></TR><TR><TDALIGN="RIGHT"VALIGN="TOP">您的工作:</TD><TD><INPUTTYPE=textNAME=job></TD></TR><TR><TDALIGN="RIGHT"VALIGN="TOP">您的留言:</TD><TD><TEXTAREANAME=commentsCOLS=40ROWS=6></TEXTAREA><P><INPUTTYPE=submitVALUE=Submit><INPUTTYPE=ResetVALUE=Reset> <AALIGN="RIGHT"HREF="guestbook.php3?action=view"onMouseOver="window.status='Readallcommentsfirst';returntrue"onMouseOut="window.status='';returntrue"TITLE="Readallcommentsfirst"><FONTSIZE="-2">先观看所有的留言</FONT></A></TD></TR></FORM></TABLE></CENTER>
<?}
/*action=send:addthedatafromtheuserintothedatabase*/elseif($action=="send"){
/*checkifaHTML-mailshouldbesendoraplain/textmail*/if($html_mail=="yes"){mail("$admin_name<$admin_mail>","PHP3GuestbookAddition","<HTML><BODY><FONTFACE="CenturyGothic"><TABLEBORDER="0"WIDTH="100%"CELLSPACING="4"><TR>$name($email)schreefhetvolgendeberichtinhetgastenboek:</TR><TR><TDALIGN="LEFT"></TD><TDALIGN="LEFT"NOWRAP></TD></TR><TR><TDALIGN="LEFT">$comments</TD><TDALIGN="LEFT"NOWRAP></TD></TR><TR><TDALIGN="LEFT"></TD><TDALIGN="LEFT"NOWRAP></TD></TR><TR><TDALIGN="LEFT">您的留言:</TD><TDALIGN="LEFT"NOWRAP>$name</TD></TR><TR><TDALIGN="LEFT">您的大名:</TD><TDALIGN="LEFT"NOWRAP>$email</TD></TR><TR><TDALIGN="LEFT">您的email:</TD><TDALIGN="LEFT"NOWRAP>$job</TD></TR><TR><TDALIGN="LEFT">您的工作:</TD></TR></TABLE></BODY></FONT></HTML>","From:$name<$email>nReply-To:$name<$email>nContent-type:text/htmlnX-Mailer:PHP/".phpversion());}
/*MySQLreallyhatesitwhenyoutrytoputthingswith'or"charactersintoadatabase,sostripthese...*/$comments=addslashes("$comments");$query="INSERTINTOguestbookVALUES('','$name','$email','$job','$comments')";$result=MYSQL_QUERY($query);
?><BR><PALIGN=CENTER>感谢,<?phpecho$name;?>,您的留言.<BR><PALIGN=CENTER><AHREF="guestbook.php3?action=view"onMouseOver="window.status='Viewyourcommentnow';returntrue"onMouseOut="window.status='';returntrue"TITLE="Viewyourcommentnow">观看留言</A><BR><BR><?
}
/*ifthere'snoactiongiven,thenwemustshowthemainpage*/else{
/*getthenumberofentrieswrittenintotheguestbook*/$query="SELECTnamefromguestbook";$result=MYSQL_QUERY($query);$number=MYSQL_NUMROWS($result);
if($number==""){$entry="还没有人留过言";}
elseif($number=="1"){$entry="目前留言人数1人";}
else{$entry="目前留言人数$number人";}
echo"<CENTER><BR>";echo"<P>$entry<BR>";echo"<H4><FONTFACE="Verdana"SIZE="3"><AHREF="guestbook.php3?action=add"onMouseOver="window.status='请您留言';returntrue"onMouseOut="window.status='';returntrue"TITLE="Addyournametoourguestbook">请您留言</A></FONT></H4>";
if($number>""){echo"<H4><FONTFACE="Verdana"SIZE="3"><AHREF="guestbook.php3?action=view"onMouseOver="window.status='观看留言';returntrue"onMouseOut="window.status='';returntrue"TITLE="Viewthenamesinourguestbook">观看留言</A></FONT></H4>";}echo"</P></CENTER>";}?><BR><SMALL><CENTER>版权所有:<AHREF="http://personal.668.cc/haitang/index.htm"onMouseOver="window.status='pert';returntrue"onMouseOut="window.status='';returntrue"TITLE="pert">无边天际</A></CENTER></SMALL></FONT></BODY></HTML>