Benas.M Benas.M - 7 months ago 26
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:`

<?php
$con=mysqli_connect("localhost","username","password","database");
$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!';
}

else{


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


mysqli_close($con);
?>`


Error:




Warning: mysql_num_rows() expects parameter 1 to be resource, object given in
/home/t1bm/domains/t1bm.us.lt/public_html/register.php on line
11


Username doesnt exist!

Answer

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!';
}