1

连接成功 致命错误:在第 7 行对非对象调用成员函数 prepare()。为什么会出现此错误?这是论坛的开始。我准备用'if ($query = $db->prepare($sql))。

<?php
session_start();
$db = mysql_connect("localhost","root","","my_db") or die ("Could not connect to         database.");
echo 'Connected Successfully';

$sql = "SELECT forum_id, forum_name FROM forum_tbl";
if ($query = $db->prepare($sql)){
    $query->bind_result($f_id, $f_name);
    $query->execute();
    $query->store_result();
}else{
    echo $db->error;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<head>
<title>Forum</title>
<meta/>
<style type="text/css">
</style>
</head>

<body>
<div class="container">
<div class="content">
    <table align="center" width="80%">
        <?php
        if($query->num_rows !==0):
        while($row = $query->fetch()):?>
        <tr>
        <td><a href="forum.php?id=<?php echo $f_id?>"><?php echo $f_name;?>    </a></td>
        </tr>
        <?php endwhile; endif;?>    
    </table>
</div>
</div>
</body>
</html>
4

2 回答 2

4

您正在mysql_connect与 PDO 混淆。使用 PDO,您将获得一个用于查询的对象,但mysql_connect无论如何都不推荐使用它!

所以你正在调用一个不是对象的方法。假设您有这样的常量(否则只需用正确的值替换)将您的代码更改为

$db = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
于 2012-12-30T23:06:30.523 回答
4

改变:

$db = mysql_connect("localhost","root","","my_db") or die ("Could not connect to database.");

try {
    $db = new PDO(mysql:dbname=my_db;host=127.0.0.1, "root","");
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
    exit();
}
于 2012-12-30T23:07:55.370 回答