drkwpgrdb092239314
drkwpgrdb092239314
2011-08-10 05:42

PHP MySQL连接错误

  • linux
  • php
  • mysql

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!

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐

换一换