Error on calling a function with connection to SQL server - php

I am getting
Fatal error: Call to a member function query() on a non-object in
C:...\test.php on line 27
after calling callQuery2.
<?php
dbConnect();
callQuery1();
callQuery2();
function callQuery1(){
// SQL query
$q = "SELECT * FROM table1 WHERE name like 'john%' ";
// Execute query
$data1 = exeQuery($q);
}
function callQuery2(){
// SQL query
$q = "SELECT * FROM table2 WHERE event = 'holiday' ";
// Execute query
$data2 = exeQuery($q);
}
// Execute SQL Query
function exeQuery($qry) {
global $pdo;
####### LINE 27 #######
$stmt = $pdo->query($qry);
if($stmt = $pdo->prepare($qry)) {
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return $data;
}
}
// database connection
function dbConnect(){
$DBSERVER = "***";
$DBUSER = "***";
$DBPASS = "***";
$DBNAME = "***";
// OBDC
try {
$pdo = new PDO("odbc:DRIVER={SQL Server};Server={$DBSERVER};Database={$DBNAME}", $DBUSER, $DBPASS);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex) {
//die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));
}
}
?>
Why the error only appears after at that time?
Is the a better way to do this?
Regards,
Elio Fernandes

This would be better encapsulated without the global $pdo; part. Instead return the PDO object from your connect method, and pass it to the others, to be used.
N.B. I've deliberately given the variables different names in different places, to illustrate that the name doesn't have to be the same when it's passed from one scope to another, it's the object that's passed which is important. You might perhaps consider using consistent names though, to make it easier to comprehend the code later, and trace the object through the flow.
<?php
$dbConn = dbConnect();
callQuery1($dbConn);
callQuery2($dbConn);
function callQuery1($db){
// SQL query
$q = "SELECT * FROM table1 WHERE name like 'john%' ";
// Execute query
$data1 = exeQuery($q, $db);
}
function callQuery2($db){
// SQL query
$q = "SELECT * FROM table2 WHERE event = 'holiday' ";
// Execute query
$data2 = exeQuery($q, $db);
}
// Execute SQL Query
function exeQuery($qry, $pdo) {
####### LINE 27 #######
$stmt = $pdo->query($qry);
if($stmt = $pdo->prepare($qry)) {
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return $data;
}
}
// database connection
function dbConnect(){
$DBSERVER = "***";
$DBUSER = "***";
$DBPASS = "***";
$DBNAME = "***";
// OBDC
try {
$pdo = new PDO("odbc:DRIVER={SQL Server};Server={$DBSERVER};Database={$DBNAME}", $DBUSER, $DBPASS);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
catch(PDOException $ex) {
//die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));
}
}
?>

Related

php add prepared statements to database

I want to implement the prepared statement to my script but really cant get it to work. I already have alot of functions so i want as little change as possible.
I think it would be best to have a prepared statement function? So when i get user inputs I could call that functions instead of query.
The database.php class
class MySQLDB {
var $connection; // The MySQL database connection
/* Class constructor */
function MySQLDB() {
global $dbsystem;
$this->connection = mysqli_connect ( DB_SERVER, DB_USER, DB_PASS, DB_NAME ) or die ( 'Connection Failed (' . mysqli_connect_errno () . ') ' . mysqli_connect_error () );
}
/**
* query - Performs the given query on the database and
* returns the result, which may be false, true or a
* resource identifier.
*/
function query($query) {
return mysqli_query ( $this->connection, $query );
}
};
/* Create database connection */
$database = new MySQLDB ();
this is how I call the database from another class.
$q = "UPDATE users SET name = '$name', started = '$time' WHERE id = '$id';";
$result = mysqli_query ( $database->connection, $q );
In your case I would do something a little cleaner, like this:
<?php
class MySQLDB{
private function openConnection(){
// If you don't always use same credentials, pass them by params
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Assign conection object
return $conn;
}
private function closeConnection($conn){
$conn->close();
}
function updateUserById($id, $name, $startedTime){
$conn = $this->openConnection();
$sqlQuery = "UPDATE users SET name = ?, started = ? WHERE id = ?";
if ($stmt = $conn->prepare($sqlQuery)) {
// Bind parameters
$stmt->bind_param("ssi", $name, $startedTime, $id);
// Execute query
$stmt->execute();
if ($stmt->errno) {
die ( "Update failed: " . $stmt->error);
}
$stmt->close();
}
$this->closeConnection($conn);
}
} // Class end
Now, to use it, you just have to do this:
<?php
$myDBHandler = new MySQLDB;
$myDBHandler->updateUserById(3, "Mark", 1234);

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

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
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;
}
}

How to build and call a simple PHP class for a PDO DB connection

Here's what I have so far:
class DB {
var $DBUser = 'xxx';
var $DBPass = 'xxx';
var $DBServer = 'xxx';
var $DBName = 'xxx';
public function connect() {
try {
$strDSN = "mysql:host=$this->DBServer;dbname=$this->DBName;";
$username = $this->$DBUser;
$pass = $this->$DBPass;
$conn = new PDO($strDSN, $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'connected';
}
catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
} //end method
} //end class
Which is then called using this:
$db = new DB;
$conn = $db->connect;
$stmt = $conn->prepare('SELECT * FROM XXX WHERE id = :id');
$id = $_GET['id'];
$stmt->execute(array('id'=>$id));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
However, I'm getting this error message:
Fatal error: Call to a member function prepare() on a non-object
Any ideas what I'm doing wrong?
When you call a method, include the parenthesis:
$conn = $db->connect();
// ^^ missing
The second problem is your connect method doesn't return the connection handle. In the try block add:
return $conn;
Finally, when referencing instance and class properties, don't include the $.
$username = $this->DBUser;
// ^ $ should not be present

Function returns boolean not string

What I want is to return MYSQL query in a array however my code returns a bool(true).
Here is the code from code.php
require('model.php');
$id = $_POST['id'];
$password = $_POST['password'];
$user = new user();
$row = $user->check_user($id, $password);
var_dump($row);
Here is the code from model.php
class config {
public $dbhost = "localhost";
public $dbuser = "root";
public $dbpass = "";
public $dbused = "dbname";
function dbconn() {
$conn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass,$this->dbused);
if(mysqli_connect_errno()) {
printf("Connection failed: " . mysqli_connect_error());
exit();
}
return $conn;
}
}
class user {
function check_user($id, $pass) {
$config = new config();
$conn = $config->dbconn();
$query = $conn->prepare("SELECT id, password, status FROM e_users WHERE id = ? AND password = ?");
$query->bind_param('is', $id, $pass);
try {
$query->execute();
return $query->fetch();
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I think the problem is in the $query->fetch(); because I tried return 'test'; and it works fine. Even return an array works fine.
Can anyone help me?
As The Blue Dog pointed out, fetch() returns a status flag, not the row itself. But fetch_assoc() will return a row.
Have a look here:
http://php.net/manual/en/mysqli-stmt.fetch.php
If you work with fetch, you need to bind the variables:
$stmt->bind_result($mySelectedValue_1, $mySelectedValue_2);
Here are examples with fetch_assoc():
http://php.net/manual/de/mysqli.quickstart.prepared-statements.php
So this should work fine:
$row = $res->fetch_assoc();

Categories