views:

43

answers:

2

I have written a small PHP file that gets the information that was posted to it, then checks to make sure it is no empty. If it isn't empty, it checks to make sure the username doesn't already exist. If it does, it redirects. If not, it adds the information to the MySQL database. I don't know what the problem is, but when attempting to navigate to it after pressing the submit button on the form, the browser displays an error saying that the page cannot be displayed. Here is the code.

<?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");
}
?>
+4  A: 

You are not executing the query:

$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.

Something like:

$query="SELECT username FROM members WHERE username=$username";
if(($result = mysql_query($query)) !== false) {
  if (mysql_num_rows($result) > 0 ) {
   .....
  }
}
codaddict
I have tried both solutions, but the script is still not working. Maybe another error in my script?
Zachary Brown
Ok, sorry. I figured it out... I had a typo. I am however having a problem. I used your ( @codaddict ) script there, but now when the username is already taken, it just displays a message saying duplicate entry.... I need it to redirect to register.php?invalid
Zachary Brown
+2  A: 

Change this

if (mysql_num_rows($username) > 0 ) {

to

if (mysql_num_rows(mysql_query($query)) > 0 ) {
JapanPro
Its always better to check the return value of mysql_query before you proceed. That makes debugging easier.
codaddict
thats right but i think something wrong in one line , so lets give solution on that wrong line , if it works
JapanPro
I have tried both solutions, but the script is still not working. Maybe another error in my script?
Zachary Brown
can you post in jsfillde.net and share url, i can advise further
JapanPro