我正在使用sql数据库设置Web服务器 一直在观看视频,直到出现此问题为止一切正常
<?php
function user_exists($username) {
$username = sanitize($username);
$con = mysqli_connect('localhost', 'root', '');
$query = mysqli_query("SELECT COUNT (`id`) FROM users WHERE username = '$con,$username'");
return (mysqli_result($query, 0) == 1) ? true : false;
}
?>
可恢复的致命错误:
无法将mysqli类的对象转换为字符串 第5行的C:\ xampp \ htdocs \ login \ core \ functions \ users.php
注意 :-我已从此视频中引用,但我将mysql_*
更改为mysqli_*
[https://www.youtube.com/watch?v=Til3oVNlho4] < / p>
答案 0 :(得分:4)
一些注意事项,
global
或在函数内创建连接)。mysqli_result()
不是mysqli_
中存在的功能。它仅存在于mysql_
中,已弃用,不应使用。$count == 0
而不是$count == 0 ? true : false
,因为它们是等效的。 function user_exists($username, $conn) {
$stmt = $conn->prepare("SELECT COUNT(id)
FROM users
WHERE username=?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($count);
$stmt->fetch();
$stmt->close();
return $count == 0;
}
现在,在调用它时,请记住传递$conn
参数(或任何定义为连接对象的参数)。
$conn = mysqli_connect('localhost', 'root', 'root', 'databasename'); // Change credentials accordingly
if (user_exists($username, $conn)) {
// User does exist!
} else {
// User does not exist
}
答案 1 :(得分:0)
您尚未在mysqli_connect函数中传递数据库名称,并且需要将连接变量作为第一个参数传递。您可以从查询中删除COUNT
,然后使用mysqli_num_rows来计算行数。
$username = sanitize($username);
$con = mysqli_connect('localhost', 'root', '','databasename');//<- database name is required
$query = mysqli_query($con,"SELECT (`id`) FROM users WHERE username = '$username'");
return (mysqli_num_rows($query) > 0 ) ? true : false;
我建议您使用prepared statements防止SQL注入
答案 2 :(得分:0)
使用mysqli_fetch_row()函数。它将获取一行
<?php
function user_exists($username) {
$username = sanitize($username);
$con = mysqli_connect('localhost', 'root', '');
$query = mysqli_query($con,"SELECT COUNT (`id`) FROM users WHERE username = '$username'");
$result = mysqli_fetch_row($query);
return ($result[0] == 1) ? true : false;
}
?>