2013-07-18 55 views
-4

我是新来的PHP,我试图使用php和mysql做一个简单的注册表单。 我按照教程,但它似乎并没有工作。
这里是我的代码:注册表单不起作用

con.php

<?php 
    $host = "******"; 
    $user = "******"; 
    $pass = "******"; 
    $db = '******'; 

    $con = mysql_connect($host,$user,$pass) or die('could not connect to database.'); 

    mysql_select_db($db,$con) or die('could not find database'); 
?> 

register.php

<?php 
    include "con.php"; 
    $username = $_POST['user_name']; 
    $password = md5($_POST['password']); 
    $first = $_POST['first']; 
    $last  = $_POST['last']; 
    $insert = "insert into users (user_name,password,first,last) values(".$username.",".$password.",".$first.",".$last.")"; 
    mysql_query($insert) or die("Sorry could not complete signup"); 
    echo 'Signup succsessfull'; 
?> 

HTML

<form action='register.php' method='post'> 
     <div style='color:orange;'>First name:</div> 
     <input type='text' name='first' value='<?php if(isset($_POST["first"])){echo $_POST["first"];}?>'> 
     <div style='color:orange;'>Last name:</div> 
     <input type='text' name='last' value='<?php if(isset($_POST["last"])){echo $_POST["last"];}?>'> 
     <div style='color:orange;'>User name:</div> 
     <input type='text' name='user_name' value='<?php if(isset($_POST["user_name"])){echo $_POST["user_name"];}?>'> 
     <div style='color:orange;'>Password:</div> 
     <input type='password' name='password'> 
     <input type='reset' value='Reset'> 
     <input type='submit' value='Submit'> 
    </form> 

如果有人能帮助解决这个问题,那将是非常好的,因为我不能。

+4

您正在使用[an **过时的**数据库API](http://stackoverflow.com/q/12859942/19068)并应使用[现代替换](http://php.net/manual/) EN/mysqlinfo.api.choosing.php)。你也**易受[SQL注入攻击](http://bobby-tables.com/)**,现代的API会使[防御]更容易(http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php)自己从。 – Quentin

+1

您也[容易受到XSS](https://en.wikipedia.org/wiki/Cross-site_scripting) – Quentin

+0

使用PDO,其实很简单。 – Callombert

回答

2
$insert = "insert into users (user_name,password,first,last) values(".$username.",".$password.",".$first.",".$last.")"; 

SQL中的字符串值必须加引号。你没有引用你的数据。

移至使用in this answer所述的准备好的语句和绑定变量,并且数据库API将负责为您添加引号。

+1

此外,这个“回声'注册succsessfull';”只是输出注册成功,它不会告诉你插入是否成功。 – Callombert

1

查询更改为如下

$insert = "insert into users (user_name,password,first,last) values('".$username."','".$password."','".$first."','".$last."')"; 

我想你已经selectd场的varchar数据类型,所以你必须为单引号添加到每个变量。