简体   繁体   English

PHP MySQL 连接错误

[英]PHP MySQL connection error

guys.I got a littile trouble.伙计们,我遇到了一个小麻烦。
There is connection.inc.php in "includes" folder: “包含”文件夹中有 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

I use Linux for this test,and the lastest xampp 1.7.4我使用 Linux 进行此测试,最新的 xampp 1.7.4
But things become worse when I use the following code:(I already have created my DB, and two users 'readuser' and 'writeuser')但是当我使用以下代码时情况变得更糟:(我已经创建了我的数据库,以及两个用户'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";
?>

And when I load it in my browser:当我在浏览器中加载它时:
Fatal error:Call to a member function query() on a non-object in /opt/lampp/htdocs/mysqli.php on line 9致命错误:在第 9 行的 /opt/lampp/htdocs/mysqli.php 中的非对象上调用成员 function query()
So I guess $conn is not a object now,but It works when I write this code:所以我猜 $conn 现在不是 object,但是当我编写这段代码时它可以工作:

<?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";
?>

And it outputs:We have 8 pictures in DB它输出:我们在 DB 中有 8 张图片
That's really a strange thing,I can't figure it out...Thanks guys!这真是一件奇怪的事情,我无法弄清楚......谢谢大家!

Try saving the new mysqli() result as a variable, then return that variable instead.尝试将新的 mysqli() 结果保存为变量,然后返回该变量。 That logic makes no sense, I know, but I've had problems like that before.我知道,这种逻辑毫无意义,但我以前也遇到过这样的问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM