I am using following code which is not working for me.
$con=mysqli_connect(\"localhost\",\"root\",\"\",\"my_db\");
$check=\"SELECT COUNT(*) FROM persons WHER
You can try the following code:
$query_code = "SELECT COUNT(itemCode) FROM masterData WHERE itemCode='{$itemCode}'";
$result_login = mysqli_query($conn,$query_code);
$anything_found = mysqli_num_rows($result_login);
if($anything_found > 0) {
$formOk = false;
echo "ITEM CODE ALREADY EXISTS! Please try again.";
}
this code works fine for you...
$con=mysqli_connect("localhost","root","","my_db");
$check="SELECT * FROM persons WHERE Email = '$_POST[eMailTxt]'";
$rs = mysqli_query($con,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
echo "User Already in Exists<br/>";
}
else
{
$newUser="INSERT INTO persons(Email,FirstName,LastName,PassWord) values('$_POST[eMailTxt]','$_POST[NameTxt]','$_POST[LnameTxt]','$_POST[passWordTxt]')";
if (mysqli_query($con,$newUser))
{
echo "You are now registered<br/>";
}
else
{
echo "Error adding user in database<br/>";
}
}
mysqli_query
returns a mysqli_result
object. Rather than comparing this to an integer try using num_rows
:
$res = mysqli_query($con,$check);
if($res->num_rows){
//User exists
}
Edit: The above assumed the query was using SELECT *
and this will not work with SELECT COUNT(*)
. Checkout Aleks G's answer.
mysqli_query
function returns a resultset handle. You then need to read the rows from it:
$rs = mysqli_query($con,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
//user exists;
}
Also note that SELECT count(1) FROM ...
will be faster than SELECT count(*) FROM ...
You won't see much of a difference in a small table, but with a large table of several hundred thousand rows, the difference may be significant.