gpt4 book ai didi

mysqli - fatal error : Call to a member function query() on a non-object in

转载 作者:行者123 更新时间:2023-12-02 06:50:51 24 4
gpt4 key购买 nike

fatal error :在线非对象上调用成员函数 query():$result = $conn->query($sql) 或 die(mysqli_error());

谁知道出了什么问题以及如何修复它?

<?php
function dbConnect($usertype, $connectionType = 'mysqli') {
$host = 'localhost';
$db = 'phpsols';
if ($usertype == 'read') {
$user = 'psread';
$pwd = '123';
} elseif ($usertype == 'write') {
$user = 'pswrite';
$pwd = '123';
} else {
exit('Unrecognized connection type');
}
if ($connectionType == 'mysqli') {
return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
} else {
try {
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch (PDOException $e) {
echo 'Cannot connect to database';
exit;
}
}
}

// connect to MySQL
$conn = dbConnect('read');
// prepare the SQL query
$sql = 'SELECT * FROM images';
// submit the query and capture the result
**$result = $conn->query($sql) or die(mysqli_error());**
// find out how many records were retrieved
$numRows = $result->num_rows;
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Connecting with MySQLi</title>
</head>

<body>
<p>A total of <?php echo $numRows; ?> records were found.</p>
</body>
</html>

最佳答案

罪魁祸首很可能是这一行:

return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');

do xyz or die() 构造与 return 语句结合使用会导致有趣的行为(即整个事情被解释为 OR 表达式,并且因为 new mysqli 永远不会为假,“die”永远不会被处理。)。查看类似案例here .

这样做:

$result = new mysqli($host, $user, $pwd, $db) ;
if (!$result) die (....);
return $result;

此外,稍微相关的是,我认为您永远不会捕获 PDO 连接错误,因为:

return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);

总是退出函数,并且永远不会到达catch block 。与您的实际问题一样,解决方案是首先将对象传递给 $result 变量。

关于mysqli - fatal error : Call to a member function query() on a non-object in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4633799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com