Benas.M Benas.M - 1 year ago 60
SQL Question

PHP MySQL duplicated value checker

My goal is to check if same username already exists and if so, to prevent it from registering. Don't know why my code doesn't work.

My code:`

$username = $_POST['username'];
$password = $_POST['password'];

$query = mysqli_query($con, "SELECT * FROM user WHERE username='$username'");

if(mysql_num_rows($query) > 0){

echo 'Username already exists!';


echo 'Username doesnt exist!';
$sql_query = "insert into user values('$username','$password', 'null', 'null');";
mysqli_query($con, $sql_query) or die (mysqli_error($con));



Warning: mysql_num_rows() expects parameter 1 to be resource, object given in
/home/t1bm/domains/ on line

Username doesnt exist!

Answer Source

Use mysqli_num_rows . mysql_num_rows was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.

Try this:

if(mysqli_num_rows($query) > 0){

 echo 'Username already exists!';