drkwpgrdb092239314 2011-08-10 05:42
浏览 79
已采纳

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条回答 默认 最新

  • dtcwehta624485 2011-08-10 05:50
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?