我做不到,所以数据存储在mysql数据库中

时间:2013-11-01 20:33:05

标签: php html mysql database

所以,我有一个.php文件,用于检查某人的用户名是否可用,然后将其存储在数据库中,'check'部分工作,然后将用户重定向到正确的页面,但是,数据未存储在数据库中。

它引用的表单来自用户单击的文件,以实际启用此.php文件。

(我标记了应该在mysql数据库中存储数据的代码部分)

<?php

$host="localhost"; 
$username="root";  
$password="___________"; 
$db_name="test_database"; 
$tbl_name="members";

mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

$username=$_POST['username'];
$password=$_POST['password'];
$email=$_POST['email'];

$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$sql="SELECT * FROM $tbl_name WHERE username='$username'";
$result=mysql_query($sql);

$count=mysql_num_rows($result);

// If result matched $myusernametable row must be 1 row
if($count==1){

header("location:register_failure.html");
}
else {
$username=$_POST['username'];//Start of code which should store data in database
$password=$_POST['password'];
$email=$_POST['email'];
$sql = "INSERT INTO members (username, password, email) VALUES ('$username',                                    
'$password', '$email')";//End of code which should store data in database
header("location:register_success.html");
}
?>

3 个答案:

答案 0 :(得分:1)

您已将INSERT语句分配给$ sql,但实际上并未运行它。在$ sql赋值和header语句之间添加这一行:

$result=mysql_query($sql);

我还强烈建议在那里添加一些错误检查。现在,即使查询失败,用户仍然会被重定向到成功页面。

答案 1 :(得分:0)

用这个替换你的else命令:

else {
$username=$_POST['username'];//Start of code which should store data in database
$password=$_POST['password'];

$email=$_POST['email'];

$addsql = "INSERT INTO members (username, password, email) VALUES ('$username', '$password', '$email')";
$dosql = mysql_query($addsql);
header("location:register_success.html");
}

答案 2 :(得分:0)

我认为如果你返回已执行的sql语句的状态会更好,如:

else {
$username=$_POST['username'];//Start of code which should store data in database
$password=$_POST['password'];
$email=$_POST['email'];
$sql = "INSERT INTO members (username, password, email) VALUES ('$username', '$password', '$email')";
$result = mysql_query(sql);
if (!$result) {
    die('SQL Error: ' . mysql_error());
}
header("location:register_success.html");
}

所以用户知道,如果注册成功与否;) 你也可以删除“die”部分并用邮件替换它, 所以如果您的注册出现问题,您会被注意到。