Jump to content

mysqli alternative for mysql_result


clickbeast
Go to solution Solved by jcbones,

Recommended Posts

Hello,

 

I am new to mysqli and have a little question. I have tried to find an alternative for a while now but nothing seems to work... maybe somebody could help.

 

So my old code is this

 

 
function ($email) {
$query = mysql_query("SELECT COUNT(`user_id`) FROM users WHERE email = '$email'")or die (mysql_error());
return (mysql_result($query, 0) == 1) ? true : false;
}
 
after that the function is used like this : 
if (login_email_exists($mysqli,$_POST['email']) === true) {
$errors[] = 'Sorry this email adress is already in use.';
}
 
And my new code is this 
 
function ($mysqli,$email) {
$query = $mysqli->query("SELECT COUNT(`user_id`) FROM users WHERE email = '$email'")or die (mysql_error());
return ($query == 1) ? true : false;
}
 
Now it seems to always go wrong when I want to check the result and return if it's true or false. If anybody can find an answer or alternative to my problem I would be very happy.
 
Link to comment
Share on other sites

  • Solution

I suggest preparing the data for database interaction instead of using the simple query() function.  The reason being is that the class does a great job with sanitation, and validation when using the bind_param() method.

 

 

 
function login_email_exists($mysqli,&$email) {
if(!$query = $mysqli->prepare("SELECT COUNT(`user_id`) FROM  users WHERE email = ?")) {
trigger_error($mysqli->error);
}
$query->bind_param('s',$email);
$query->execute();
$query->bind_result($count);
$query->fetch();
return ($count > 0) ? true : false;
}
Edited by jcbones
Link to comment
Share on other sites

return ($count > 0) ? true : false;

 

Pro tip:if you are using a condition and want a Boolean as the result, there is no need to actually create a TRUE and FALSE for the result because the condition itself will be a Boolean. That is basically the same as saying If true, return true, else return false.

 

This will work just the same to return a Boolean:

 

return ($count > 0);
Edited by Psycho
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.