PHP PDO Common Error i Faced - php

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

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

Failed to select data from PHPMyAdmin using PHP PDO

This is my code:
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
?>
But, when I run it, nothing gets printed. What's wrong?
Yes, my table is not empty. I am 100% able select & print data using MySQLi Object-oriented, but not working with PDO. What's wrong in my code?
Call the function
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
//call the function here
printResult($conn);
?>
To run a function you must call it.
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
// and if this fails there is no point continuing so add an exit
exit;
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
printResult($conn); // call the function
?>
You don't call function printResult from anywhere.
Add to your code printResult($conn);

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

Using a function in php to create a database connection?

So really I just want to make stuff easier to read and just create a function where I can call upon the database connection, the below is what i've tried to do to do far.
So far, it doesn't work, it doesn't bring any message at all so presumably it isn't going into the try.
functions.php
function getDBConnection()
{
try
{
$db = new PDO('mysql:host=localhost;dbname=name;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
}
catch(PDOException $e)
{
echo 'An error occured talking to the DB';
}
return $db;
}
and then do
submittest.php
require('functions.php');
getDBConnection(); //return $db
$username = 'donkey';
$password = 'donkey';
$email = 'donkey';
$county = 'donkey';
try
{
//Prepare and execute an insert into DB
$st = $db->prepare("INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:county)");
$st->execute(array(':username' => $username, ':password' => $password, ':email' => $email, ':county' => $county));
echo 'Success';
}
catch (PDOException $e)
{
echo 'An error occurred talking to the DB';
}
?>
$db = getDBConnection(); //return $db

Categories