1

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");
}
?>

2 Answers 2

5

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 ) {
   .....
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I have tried both solutions, but the script is still not working. Maybe another error in my script?
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
2

Change this

if (mysql_num_rows($username) > 0 ) {

to

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

4 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.