问题
As a part of a login system I need to check if the username exists in the database so I created a query that checks if the username the user entered already exists.
With mysql_result
I check if the id is larger as null. If yes: user exists and if not the user doesn't exist. But here it goes wrong and wampserver gives me this error:
Warning: mysql_result() expects parameter 1 to be resource, object given in users.php on line 6
function user_exists($username){
global $user_db;
$username = sanitize($username);
$query = mysqli_query($user_db , "SELECT COUNT(`id`) FROM `users` WHERE `username` = '$username'");
$result = mysql_result($query, 0); //line 6
if(!$result){
return false;
}else{
return true;
}
}
and this is the code that calls that function:
if(user_exists('name') === true){
echo 'exists';
}
$user_db = mysqli_connect("localhost","root","","databaseName");
What did I try:
if I do this: mysqli_result($result,0,"id");
I get this error: Call to undefined function mysqli_result()
.
got this suggestion from this question
All the answers on questions like mine say that you should not use mysql
and mysqli
both but only one of them but when I only use mysli
I get the error like I told one paragraph above this one.
So can somebody tell me how to fix this.
回答1:
You are mixing mysql and mysqli a bit. There is no function mysqli_result() in mysqli driver. However I found a solution to your problem. From comment in PHP documentation:
Converting an old project from using the mysql extension to the mysqli extension, I found the most annoying change to be the lack of a corresponding mysql_result function in mysqli. While mysql_result is a generally terrible function, it was useful for fetching a single result field value from a result set (for example, if looking up a user's ID).
The behavior of mysql_result is approximated here, though you may want to name it something other than mysqli_result so as to avoid thinking it's an actual, built-in function.
The code:
<?php function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field]; }
?>
Source: http://php.net/manual/en/class.mysqli-result.php
来源:https://stackoverflow.com/questions/30681644/mysql-result-expects-parameter-1-to-be-resource-object-given