对null的PDO MSSQL错误查询

时间:2015-06-09 05:16:14

标签: php mysql sql-server pdo

我正在尝试从我的数据库表中选择行,并且我收到一条错误,指出

Fatal error: Call to a member function query() on null in..

我们与数据库的连接显示成功。下面是我的PHP代码:

<?php
   require_once("dbconn.php");
   $db = getConnection();

   $input_pid = "870104-07-5448";
   $sql = "SELECT * FROM Pat WHERE PID ='$input_pid'";
   $stmt = $db->query($sql);
   $row = $stmt->fetchObject();
   echo $row->PID;
   echo $row->Name;
?>

这是dbconn.php代码:

function getConnection(){
try {
    $hostname = "busctrlctr-pc";
    $dbname   = "DispenserSystem";
    $username = "sa";
    $password = "123456";
    $db = new PDO ("sqlsrv:Server=$hostname;Database=$dbname", $username, $password);
    echo 'We are succesful to connect the database !!'.'<br>'; // successful word
} catch (PDOException $e){
    echo "connection failed problem is >> ". $e -> getMessage()."\n";
    exit;
}

}

我能知道为什么会收到此错误。谢谢。

1 个答案:

答案 0 :(得分:1)

您永远不会在$db;

功能中返回getConnection()

将功能更改为:

function getConnection(){
try {
    $hostname = "busctrlctr-pc";
    $dbname   = "DispenserSystem";
    $username = "sa";
    $password = "123456";
    $db = new PDO ("sqlsrv:Server=$hostname;Database=$dbname", $username, $password);
    echo 'We are succesful to connect the database !!'.'<br>'; // successful word
    return $db;
} catch (PDOException $e){
    echo "connection failed problem is >> ". $e -> getMessage()."\n";
    exit;
}
}