开发者

PHP MySQL connection error

guys!I got a littile trouble.

There is connection.inc.php in "includes" folder:

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

But things become worse when I use the following code:(I already have created my DB, and two users 'readuser' and '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

So I guess $conn is not a object now,but It works when I write this code:

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

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. 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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜