PDO MSSQL error query on null - php

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
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:
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();
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;
}
}

Related

database connect issues

Hello could anyone help me please with db connection, im using xampp, phpmyadmin, when i open the browser, DBConnection.class.php it shows blank and db doesnt work, thanks
<?php
class DBConnection{
public static function DbConn(){
$servername = "mysql:host=localhost;dbname=test";
$username = "root";
$password = "";
try{
$conn = new PDO($servername, $username, $password);
return $conn;
echo"Connection succesful :)";
}
catch (PDOException $e) {
echo "Connection failed :( :" . $e->getMessage();
}
}
}
?>
Modified Code. Try this:
class DBConnection{
public static function DbConn(){
$servername = "mysql:host=localhost;dbname=test";
$username = "root";
$password = "";
try{
$conn = new PDO($servername, $username, $password);
return "Connection succesfull :)";
//return $conn;
}
catch (PDOException $e) {
echo "Connection failed :( :" . $e->getMessage();
}
}
}
and then call like this
$Connection = new DBConnection();
print_r($Connection->DbConn());

PDO/PHP LoginScript ending in error 500 using MAMP

I've been trying for a while now to get my loginscript working and i can't seem to find the issue, either im just blind or there's something else going on here.
It doesn't matter if i input the correct credentials or not into the form, i still end up getting a lovely error 500.
Any ideas?
The DB connect funtion:
function db_connect() {
if i move this column-->
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
<---
return $conn; /added this as suggested, still returns NULL.
}
The login file:
include('../lib/functions.php'); //This is correct!
db_connect();
<-- HERE, it works -->
Earlier had an issue where my password hash during register was faulty, so password_verify($_POST['password'], $results['passw'])had no effect, always returning false even with correct input.
if(!empty($_POST['username']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT uname,passw FROM users WHERE uname = :user AND passw = :pass');
$records->bindparam(':user', $_POST['username']);
$records->bindparam(':pass', $_POST['password']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0 && password_verify($_POST['password'], $results['passw']) && $_POST['username'] == $results['uname']) //Also tried removing the &&-->username area incase two and statements were wrong without any luck {
die('It works!');
} else {
die('OR NOT!');
}
endif;
Your db_connect() function defines $conn in it's own scope. So, variable $conn is local. And after db_connect() ends executing $conn just disappears.
Outside this function $conn is simply NULL.
Return $conn to outer scope from your function:
function db_connect() {
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
return $conn; // here
}
And in your script:
include('../lib/functions.php'); //This is correct!
$conn = db_connect();
// other codes

PDO object cant acess inside function

In my project i had a file called connection.inc.php which is managing the data base connection using PDO.
include/connection.inc.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
i included this file in various other pages and it worked perfectly for me. But when i tried to acess the $conn object inside a function it not working. How to fix this problem.
You could do global $conn on top of your functions, but don't. I suggest wrapping it in a singleton instead.
<?php
class Connection {
private static $conn = null;
private $connection = null;
private function __construct() {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
try {
$this->connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage(); // Should look into a different error handling mechanism
}
}
public static function getConnection() {
if (self::$conn === null) {
self::$conn = new self();
}
return self::$conn->connection;
}
}
You can access it via Connection::getConnection()
This also has the advantage of not initializing the connection if the current request doesn't need to use it.
Honestly the simplest method is to set the connection inside of a function then you can use that function in other functions.
Example:
error_reporting(E_ALL);
ini_set('display_errors', 1);
function dataQuery($query, $params) {
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host='.DB_HOSTNAME.';dbname='.DB_DATABASE, DB_USERNAME, DB_PASSWORD);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step to close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
How To Use In Another Function:
function doSomething() {
$query = 'SELECT * FROM `table`';
$params = array();
$results = dataQuery($query,$params);
return $results[0]['something'];
}
You need to update your file as
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
//// define global variable
global $connection
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
/// assign the global variable value
$connection = $conn ;
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
Now you can call it any of your function like
function mytest(){
global $connection;
}
The best practice would be to pass the $conn as argument to the function.
But if you really need the function to have no arguments but still use a global variable, then adding this line in your function before using the variable should do the trick:
global $conn; // I want to use the global variable called $conn

PHP PDO Common Error i Faced

I gotten this error
Database Connected successfully Fatal error: Call to a member function prepare() on a non-object in D:\home\site\wwwroot\DatabaseMethods.php on line 22
I can't seem to find what is causing this any one could point out whats wrong please enlighten me.
I have tried to call the connection before running the prepared statement but cant seems to work or what should i do
Thanks in advance
DatabaseMethods.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("DatabaseConnection.php");
date_default_timezone_set("Asia/Singapore");
//Register
function RegisterUser($email , $password)
{
$conn = connect_db();
$stmt = null;
$stmt = $conn->prepare("INSERT INTO secure_login (email,password,created_dt) VALUES(?,?,?)"); //ERROR LINE
$stmt->execute(array($email, $password , date("Y-m-d h:i:s")));
if( $stmt )
{
return "success";
}
else
{
return "Failed";
}
}
//date("Y-m-d h:i:s")
//End Register
?>
DatabaseConnection.php
<?php
function connect_db()
{
$servername = "xxxx";
$username = "xxx";
$password = "xxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=xxx", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Database Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
?>
Answer
<?php
function connect_db()
{
$servername = "xxx";
$username = "xxx";
$password = "xxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=xxx", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Database Connected successfully";
return $conn;
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
?>

database connection. Misunderstanding of error messages

I am receiving these error messages:
Warning: PDO::__construct() expects parameter 4 to be array, string given in C:\wamp\www\MyProjects\GhislainPOO\personnages.php on line 2. There is no password required, I am wondering what it's meant by array here?
Fatal error: Call to a member function query() on a non-object in C:\wamp\www\MyProjects\GhislainPOO\personnages.php on line 3. is $bdd not an object, although I use "new PDO"?
PHP
<?php
$bdd= new PDO ('localhost', 'POO', 'root', '');
$bdd->query( "SELECT * FROM jeux_combats");
$result = $bdd->query( "SELECT * FROM jeux_combats");
while ($donnee = $result->fetch()) {
echo '<p>'.'le personnage'.$donnee['nom'].'a une force de'.$donnee['forceperso'].'</p>';
}
?>
Please read the manual: http://php.net/manual/en/pdo.construct.php
parameter: information about the database connection
parameter: username for the connection
parameter: password for the connection
parameter: a key=>value array of driver-specific connection options (optional)
It should be like this:
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
About your second question. The error should disappear after you will fix your first problem. Anyways... You could check if $bdd is null or not if you fear that the second error could appear again even after you will fix your first problem. Something like:
if($bdd != null){
if($result = $bdd->query( "SELECT * FROM jeux_combats")){
while ($donnee = $result->fetch(PDO::FETCH_ASSOC)) {
echo '<p>'.'le personnage'.$donnee['nom'].'a une force de'.$donnee['forceperso'].'</p>';
}
}
}
The whole code in your case would be:
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$bdd = new PDO($dsn, $user, $password);
if($bdd != null){
if($result = $bdd->query( "SELECT * FROM jeux_combats")){
while ($donnee = $result->fetch(PDO::FETCH_ASSOC)) {
echo '<p>'.'le personnage'.$donnee['nom'].'a une force de'.$donnee['forceperso'].'</p>';
}
}
}
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

Categories