用户注册练习
表单文件:
1 <html>
2 <head><title>用户注册练习:表单</title>
3 <meta http-equiv="content-type" content="text/html;charset=gb2312"/>
4 </head>
5 <body>
6 <form action="zhuce.php" method="post">
7 <table border="1" width="300px">
8 <tr>
9 <td colspan="2" align="center">用户注册</td>
10 </tr>
11 <tr>
12 <td>用户名:</td>
13 <td><input type="text" name="name"/></td>
14 </tr>
15 <tr>
16 <td>密码:</td>
17 <td><input type="password" name="pwd"></td>
18 </tr>
19 <tr>
20 <td colspan="2" align="center"><input type="submit" value="注册"></td>
21 </tr>
22 </table>
23 </form>
24 </body>
25 </html>
php操作mysql文件:
<html> <head> <meta http-equiv="content-type" content="text/html;charset=gb2312"/> </head> <body> <?php if($_POST["name"]!=null) { $name=$_POST["name"]; $pwd=$_POST["pwd"]; $link=mysql_connect("localhost","root","123"); $select=mysql_select_db("madb",$link); mysql_query("set names gb2312"); $into="insert into admin (name,pwd) values('$name','$pwd')";//这一行一定要记得加引号,否则实现不了。 $insert=mysql_query($into,$link); if($insert) { echo "<script>alert('注册成功');window.location.href='001.php';</script>"; }else{ echo "<script>alert('注册失败');window.location.href='001.php';</script>"; } }else{ echo "<script>alert('请重新填写');window.location.href='001.php';</script>"; } mysql_free_result($insert);//括号里填要释放的结果标识符。该结果标识符是从 mysql_query() 返回的结果。 mysql_close($link);//关闭数据库连接。 ?> </body> </html>
(改进)对第二个文件,由于if嵌套太多代码可能导致可读性差,还可以改用三元运算符。
<html> <head><meta http-equiv="content-type" content="text/html;charset=gb2312"/></head> <body> <?php if($_POST["name"]==null) { echo "<script>alert('请填写用户名');</script>"; echo "<script>window.location.href='001.php';</script>"; }else{ $name=$_POST["name"]; $pwd=$_POST["pwd"]; $link=mysql_connect("localhost","root","123");//链接数据库服务器 $select=mysql_select_db("madb",$link);//选择数据库 mysql_query("set names gb2312"); //设置数据库编码 $into="insert into admin (name,pwd) values('$name','$pwd')"; $insert=mysql_query($into,$link); echo $insert ? "<script>alert('注册成功');window.location.href='001.php';</script>" : "<script>alert('注册失败');window.location.href='001.php';</script>";//这里用了三元运算符 } ?> </body> </html>