gpt4 book ai didi

PHP MySQL 连接错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:26 25 4
gpt4 key购买 nike

伙计们!我有点小麻烦。
“包含”文件夹中有 connection.inc.php:

<?php
function dbConnect($usertype, $connectionType = 'mysqli') {
$host = 'localhost';
$db = 'testdb';
if ($usertype == 'read') {
$user = 'readuser';
$pwd = 'testpass';
} elseif ($usertype == 'write') {
$user = 'writeuser';
$pwd = 'testpass';
} 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;
} // end of try block

} // end of $connectionType if

} // end of function

本次测试我使用Linux,最新的xampp 1.7.4
但是当我使用以下代码时情况变得更糟:(我已经创建了我的数据库,以及两个用户“readuser”和“writeuser”)

<?php
// I use mysqli extension to connect my DB
require_once(includes/connection.inc.php);
// connect to DB
$conn = dbConnect('read');
// I need to get some picture infomations from images table
$sql = 'SELECT * FROM images';

$result = $conn->query($sql) or die(mysqli_error());
// find out how many records were retrieved
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>

当我在浏览器中加载它时:
Fatal error: Call to a member function query() on a non-object in/opt/lampp/htdocs/mysqli.php on line 9
所以我猜 $conn 现在不是一个对象,但是当我写这段代码时它起作用了:

<?php
$host = 'localhost';
$user = 'readuser';
$pass = 'testpass';
$db = 'testdb';
$sql = 'SELECT * FROM images';

$conn = new mysqli($host, $user, $pass, $db);
$result = $conn->query($sql) or die(mysqli_error());
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>

它输出:我们在数据库中有 8 张图片
这真是一件奇怪的事情,我想不通...谢谢大家!

最佳答案

尝试将新的 mysqli() 结果保存为变量,然后返回该变量。我知道这种逻辑毫无意义,但我以前遇到过类似的问题。

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

关于PHP MySQL 连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7006383/

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