views:

43

answers:

2

I just started with PHP and my SQL databases, I have learned how to create databases, and create register forms that store the information on the databases, but I do not know how to keep people from being able to register with a user name that has already been taken, and I don't know how to allow users to have their own profile page on my website. Do you know how? I am using XAMPP to test my databases and PHP code on my local server, if that help in any way. Here is my PHP code:

<?php
$con=mysql_connect("localhost", "root", "" );
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
$username=$_POST['username'];
$password=$_POST['password'];
$email=$_POST['email'];

mysql_select_db("test", $con);

mysql_query("INSERT INTO users (id, username, password, email)
  VALUES (NULL,'$username', MD5('$password'), '$email')");

if (my_query) 
  echo "Account Successfully Created";
else
  echo "Sorry Could Not Create Account !";

mysql_close($con);
?>
A: 

For your first problem:

When a user attempts to sign up, before creating their account, check to ensure their desired username hasn't already been taken.

To ensure no duplicate usernames, make the username column unique

Michael Robinson
A: 

Hey,

PLEASE make sure you read up on SQL injections before continuing. It's good to get good MySQL habits early!

You'll need to change the following SQL query to fit your current database structure, but you should see the pattern of what's going on -

$getSQL = "SELECT * FROM users WHERE username = '$username';";
$getResult = mysql_query($getSQL);
if(mysql_num_rows($getResult) > 0) { // This username is already taken } else { // This is a new username }

As far as a profile page, create a viewprofile.php file that takes the user's ID, and the following code should get you going in the right direction.

$getSQL = "SELECT * FROM users WHERE id = '$id';";
$getResult = mysql_query($getSQL);
if(mysql_num_rows($getResult) > 0) {  

    // The profile being viewed exists

    while($gR = mysql_fetch_array($getResult)) {
        $userid = $gR['id'];
        $username = $gR['username'];
    }

} else { 

    // The profile being viewed doesn't exist
}

I really hope this helps you! Some other good resources for you: MySQL Tutorial, Basic User Authentication Tutorial,

Raphael Caixeta
Thank you so much!, that really did help.
Ralphs17
What is the $gr, I don't see were that is declared. Never mind I see.
Ralphs17