I have a register page and I want to ensure that usernames are unique. I have tried all the solutions on here already and nothing is working for me.
This is the error I'm currently getting:
Warning: mysqli_query() expects at least 2 parameters, 1 given
in C:\xampp\htdocs\project\projectregistered.php on line 16
Query was empty
Here is my php:
<?php
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
echo $username;
$query = mysqli_query("SELECT * FROM projectuser WHERE username='$username'");
$result1 = mysql_query($query) or die (mysql_error().$query);
$count = mysql_num_rows($result1);
if ($count>0) {
echo 'Sorry! This Username already exists!';
} else {
$surname = $_POST['surname'];
$sql = "INSERT INTO projectuser (firstname, surname, username, password, location)
VALUES
('$_POST[firstname]', '".mysql_real_escape_string($surname)."', '$_POST[username]', '$_POST[password]', '$_POST[location]')";
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added ".$sql;
mysqli_close($con);
?>
Making the
username
column unique in your MySQL table is the easiest way to achieve thisThis will prevent 2 rows having the same username, on
INSERT
orUPDATE
MySQL Reference
most mysqli_* functions expect a mysqli-instance as first parameter.
Or you can use $con->function() without extra parameter.
p.s.: Do not mix mysqli and mysql.
To ensure that the username is unique, simply add an unique-index to the column... (and check if $con->error was set)
As you're using the procedural approach, you also need to pass the connection handle as first argument. It should be
Additionally, make the
username
column in your DB tableUNIQUE
.Update:
I just realised you're using both
mysql_
as well asmysqli_
functions. Better stick to the second one. So your code would be:But as already mentioned above, if you set your
username
column asUNIQUE
you won't need that check at all. You could usemysqli_insert_id
after theINSERT
to check whether a record has been inserted or not. IF it hasn't been inserted, then theUNIQUE
constraint had fired off. This way is more efficient thanSELECT
ing first just to check whether the username already exists.