Zvonimir Rudinski Zvonimir Rudinski - 7 months ago 19
SQL Question

How can I check for duplicate usernames using PHP and MySQL?

I'm just learning PHP and I thought it would be a good idea to learn some MySQL too.So I started working on the code and for some strange reason I keep getting duplicate users which is really really bad.

$link = mysqli_connect(here i put the data);
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
{ echo "User set! "; }
else { echo "User not set!"; exit; }
if(isset($_POST['pass']) && !empty($_POST['pass']))
{ echo "Password set! "; }
else { echo "Password not set!"; exit; }
$num = mysqli_num_rows(mysqli_query("SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
if($num > 0)
{ echo "Cannot add duplicate user!"; }

For some strange reason I don't get the output I should get.I've tried some solutions found here on StackOverflow but they didn't work.


The first parameter of connectionObject is not given in mysqli_query:

$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( `username` = '".$_POST['user']."' )"));

Also, your code is vulnerable to SQL Injection. A simple fix would be:

$_POST['user'] = mysqli_real_escape_string($link, $_POST['user']);