[英]PDO MSSQL error query on null
I am trying to select rows from my database table, and I am getting an error stating that我试图从我的数据库表中选择行,但我收到一条错误消息,指出
Fatal error: Call to a member function query() on null in..
Our connection to the database shows successful.我们与数据库的连接显示成功。 Below is my php code:
下面是我的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;
?>
This is the dbconn.php code:这是 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;
}
} }
Can i know why I am getting this error.我能知道为什么我会收到这个错误。 Thank you.
谢谢你。
You never return $db
in your funtion getConnection()
;你永远不会在你的函数
getConnection()
返回$db
;
change the funtion to:将函数更改为:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.