PHP表单验证器/ MySQL插入

时间:2010-09-24 04:31:11

标签: php mysql login validation

我写了一个小的PHP文件,它获取发布给它的信息,然后检查以确保它不是空的。如果它不为空,则检查以确保用户名尚不存在。如果是,则重定向。如果没有,它会将信息添加到MySQL数据库。我不知道问题是什么,但是当在按下表单上的提交按钮后尝试导航到它时,浏览器会显示一条错误消息,指出该页面无法显示。这是代码。

<?php
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['email'];
$username = $_POST['user'];
$password = $_POST['pass'];


$con = mysql_connect("localhost","USER","PASS");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("zach_blogin", $con);

$query="SELECT username FROM members WHERE username=$username";



if (mysql_num_rows($username) > 0 ) {
  header("Location: register.php?invalid");
} else {
  $sql=("INSERT INTO members (username, password, FirstName, LastName, Email)
  VALUES ($username, $password, $firstname, $lastname, $email)");
  if (!mysql_query($sql,$con))
    {
    die('Error: ' . mysql_error());
    }
else {
  header("Location: register.php?required");
}
?>

2 个答案:

答案 0 :(得分:5)

您没有执行查询:

$query="SELECT username FROM members WHERE username=$username";
//You need to execute the query here before you get num of rows.
if (mysql_num_rows($username) > 0 ) // also mysql_num_query takes an object.

类似的东西:

$query="SELECT username FROM members WHERE username=$username";
if(($result = mysql_query($query)) !== false) {
  if (mysql_num_rows($result) > 0 ) {
   .....
  }
}

答案 1 :(得分:2)

更改此

if (mysql_num_rows($username) > 0 ) {

if (mysql_num_rows(mysql_query($query)) > 0 ) {