php操作数据库常用命令 php中数据库怎么设计( 五 )


}
?
当然 , 表user中有一个username的字段 , 这就类似asp中的
%
exec="select * from user"
set rs=server.createobject("adodb.recordset")
rs.open exec,conn,1,1
do while not rs.eof
response.write "username:"rs("username")"br"
rs.movenext
loop
%
当然先要连接数据库,一般我们 require_once('conn.php');而conn.php里面就是上一次说的连接数据库的代码 。
小小的两条命令可以完成读取数据的工作了
学会添加删除修改数据
mysql_query($exec);
单这个语句就可以执行所有的操作了,不同的就是$exec这个sql语句
添加:$exec="insert into tablename (item1,item2) values ('".$_POST['item1']."',".$_POST['item1'].")";
删除:$exec="delete from tablename where...";
修改:$exec="update tablename set item1='".$_POST['item1']."' where ...";
说到这里就要说一下表单和php变量传递 , 如果表单中的一个 input name="item1" type="text" id="item1"
表单以POST提交的,那么处理表单文件就可以用$_POST['item1']得到变量值,同样以GET提交的就是$_GET['item1']
是不是很简单?但是通常$exec会有问题,因为可能您的SQL语句会很长,您会遗漏.连接符,或者'来包围字符型字段 。
我们可以注释mysql_query($exec);语句用echo $exec;代替来输出$exec以检查正确性 。如果您还不能察觉$exec有什么错误的话,可以复制这个sql语句到phpmyadmin中执行,看看它的出错信息 。还有需要注意的是,我们不要使用一些敏感的字符串作为字段名字 , 否则很可能会出现问题,比如说date什么的 。变量的命名,字段的命名遵循一点规律有的时候对自己是一种好处,初学者并不可忽视其重要性 。
学会SESSION的使用
SESSION的作用很多,最多用的就是站点内页面间变量传递 。
在页面开始我们要session_start();开启SESSION;
然后就可以使用SESSION变量了,比如说要赋值就是:$_SESSION['item']="item1";要得到值就是$item1=$_SESSION['item'];,很简单吧 。这里我们可能会使用到一些函数,比如说判断是不是某SESSION变量为空,可以这么写:empty($_SESSION['inum'])返回true or false 。
下面综合一下前面所说的我们来看一个登陆程序,判断用户名密码是否正确 。
登陆表单是这样:login.php
table width="100%" height="100%" border="0" align="center" cellpadding="0" cellspacing="0"
tr
form action="checklogin.php" method="post"td align="center" valign="middle"table width="400" border="0" cellpadding="5" cellspacing="1" class="tablebg"
tr class="tdbg"
td colspan="2"p align="center"Administrators Login/p/td
/tr
tr class="tdbg"
tdp align="center"Username/p/td
tdp align="center"
input name="username" type="text" id="username"
/p/td
/tr
tr class="tdbg"
tdp align="center"Password/p/td
tdp align="center"
input name="password" type="password" id="password"
/p/td
/tr
tr class="tdbg"
td colspan="2"p align="center"
input type="submit" name="Submit" value="https://www.04ip.com/post/Submit"
input type="reset" name="Submit2" value="https://www.04ip.com/post/Clear"
/p/td
/tr
/table/td/form
/tr
/table
处理文件是这样
?php
require_once('conn.php');
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$exec="select * from admin where username='".$username."'";
if($result=mysql_query($exec))
{
if($rs=mysql_fetch_object($result))
{
if($rs-password==$password)
{
$_SESSION['adminname']=$username;
header("location:index.php");
}
else
{
echo "scriptalert('Password Check Error!');location.href='https://www.04ip.com/post/login.php';/script";

推荐阅读