Jump to content

mysqli alternative for mysql_result


clickbeast

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
https://forums.phpfreaks.com/topic/276593-mysqli-alternative-for-mysql_result/
Share on other sites

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;
}
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);

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.