PDO - 致命错误:在非对象上调用成员函数prepare()

时间:2014-01-14 12:10:49

标签: php mysql pdo

我是PDO的新手所以请耐心等待。我正在尝试将我的旧mysql转换为PDO,但我得到一个“致命错误:在第5行的functions.php中的非对象上调用成员函数prepare()”。

所以这是functions.php:

<?php
require('config.php');
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
function getSlug($param){
    $sth = $conn->prepare("SELECT * FROM articles WHERE slug = ?");
    $sth->execute(array($param));
    $slug = $sth->fetchAll(PDO::FETCH_ASSOC);
    return $slug;
}
?>

这是生成错误的页面:

<?php
include('functions.php');
$param = $_GET['param'];
$slug = getSlug($_GET['param']);    
?>

这似乎是导致问题的最后一行$slug = getSlug($_GET['param']);,但我无法解决,或者可能是其他地方。 感谢

1 个答案:

答案 0 :(得分:3)

您需要将$conn传递给getSlug函数,否则它不知道该变量是什么(并且您收到了错误消息):

<?php
require('config.php');
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

function getSlug($conn, $param) {
    $sth = $conn->prepare("SELECT * FROM articles WHERE slug = ?");
    $sth->execute(array($param));
    $slug = $sth->fetchAll(PDO::FETCH_ASSOC);
    return $slug;
}
?>


<?php
include('functions.php');
$param = $_GET['param'];
$slug = getSlug($conn, $param);
?>