以下是作为新手的我,自己实现的一个简单的用户注册功能,分享一下,供初学的同学参考,呵呵。
实现用户注册的功能,需要4个php页面,加入了一点点面向对象的思想。
1,form表单页面
1 2 3 4 5 6 7 8 9 10 11 12 | <html> <title>用户注册_www.jb200.com</title> <body> 注册:<br/> <form action = "registerDeal.php" method= "post" > 用户名:<input type= "text" name= "username" /><br/> 密码:<input type= "password" name= "password" /> <br/> 密码确认:<input type= "password" name= "passwordConfirm" /> <br/> <input type= "submit" value= "OK" /> </form> </body> </html> |
2,//Entity 实体类 user.php
1 2 3 4 5 6 7 8 9 10 | <?php class User{ var $username; var $password; function User($username,$password){ $ this ->username = $username; $ this ->password = $password; } } ?> |
3,//表单处理php registerDeal.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php //<a href="http://www.jb200.com/zt/include/" target="_blank" class="infotextkey">include</a> 'user.php'; //为什么不用添加呢? include 'user_crud.php' ; function save($username,$password){ echo "deal save" ; $user = new User($username,$password); $userDao = new UserDao(); $userDao->save($user); } if ($_POST[ 'username' ] != NULL && $_POST[ 'password' ] !=NULL){ if ($_POST[ 'password' ] != $_POST[ 'passwordConfirm' ]){ echo "两次密码不一样" ; } else { save($_POST[ 'username' ] ,$_POST[ 'password' ] ); } } else { echo "用户名或密码不能为空" ; } ?> |
4,初级DAO对象 user_crud.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php include 'user.php' ; class UserDao{ //处理<a href="http://www.jb200.com/db/" target="_blank" class="infotextkey">数据库</a>连接 function conn_<a href= "http://www.jb200.com/mysql/" target= "_blank" class= "infotextkey" >mysql</a>(){ mysql_connect( "localhost:3306" , "root" , "root" ) or die( "Could not connect : " . mysql_error()); print "Connected successfully" ; mysql_select_db( "forest" ) or die( "Could not select database <br/>" ); } function UserDao(){ $ this ->conn_mysql(); } function save($user){ echo( "<br/> $user->username,$user->password" ); $query = "insert into user(username,password) values ('$user->username','$user->password')" ; mysql_query($query) or die( "Could not save user <br/>" ); } } ?> |
总结及注意事项:
1,include包含文件问题,这点注意下相对路径与绝对路径,容易出错。
2,在写sql语句时,注意用引号包含起来 '$user->username',而不是这样:$user->username。
3,如果提示mysql库函数没有定义,记得在apache/install/ target=_blank class=infotextkey>apache配置中指定php.ini的路径:PHPIniDir "E:/soft_work/PHP"
另外,高手朋友肯定会建议使用外部包含文件创建数据库连接类等,有兴趣的朋友,可以自己实践下。