PHP - Call to a member function query() on null - Error [duplicate] - php

This question already has answers here:
Fatal error: Call to a member function query() on null
(2 answers)
Closed 5 years ago.
I have the following code in php for connecting to my database:
<?php
class MY_SQL{
private $username;
private $password;
private $conn;
public function __construct($SERVERNAME){
$this->username = "username";
$this->password = "password";
if($SERVERNAME == "data_"){
$server = "Servername";
}
else {
$server = $SERVERNAME;
}
// Create connection
$conn = new mysqli($server, $this->username, $this->password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
public function SQLCommand($cmd) {
if ( $this->conn->query($cmd) === TRUE ) {
echo "New record created successfully";
} else {
echo "Error: " . $cmd . "<br>" . $conn->error;
}
}
}
$sql = "INSERT INTO _test(test1, test2) VALUES ('hello','hi');";
$database = new MY_SQL("Servername");
$database->SQLCommand($sql);
?>
I get the following error:
Fatal error: Call to a member function query() on null
What is going wrong?

$this->conn = $conn; in __construct()

I would suggest you to improve your class with this example (taken from https://github.com/opencart/opencart/blob/master/upload/system/library/db/mysqli.php)
final class My_SQLi
{
private $connection;
public function __construct($hostname, $username, $password, $database, $port = '3306')
{
$this->connection = new \mysqli($hostname, $username, $password, $database, $port);
if ($this->connection->connect_error) {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno);
}
$this->connection->set_charset("utf8");
$this->connection->query("SET SQL_MODE = ''");
}
public function query($sql)
{
$query = $this->connection->query($sql);
if (!$this->connection->errno) {
if ($query instanceof \mysqli_result) {
$data = array();
while ($row = $query->fetch_assoc()) {
$data[] = $row;
}
$result = new \stdClass();
$result->num_rows = $query->num_rows;
$result->row = isset($data[0]) ? $data[0] : array();
$result->rows = $data;
$query->close();
return $result;
} else {
return true;
}
} else {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno . '<br />' . $sql);
}
}
public function escape($value)
{
return $this->connection->real_escape_string($value);
}
public function countAffected()
{
return $this->connection->affected_rows;
}
public function getLastId()
{
return $this->connection->insert_id;
}
public function isConnected()
{
return $this->connection->ping();
}
public function __destruct()
{
$this->connection->close();
}
}
$sql = "INSERT INTO _test(test1, test2) VALUES ('hello','hi');";
$mysql = new My_SQLi('host', 'user', 'password', 'db');
$result = $mysql->query($sql);

Related

Call to a member function prepare() on null use oop classes

In DB.class.php this is my database constructor"
private $database;
private $error;
private $stmt;
public function __construct()
{
$dsn = ...;
$options = array (
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->database = new PDO("$dsn, $this->user, $this->pass, $options");
} catch ( PDOException $e ) {
echo "error";
}
}
public function builder(string $sql)
{
$this->stmt = $this->database->prepare($sql);
$this->stmt->execute();
if (!$stmt) {
exit("Database query failed . . . !");
}
return $stmt;
}
and this is my User.class.php which is extended, my database class:
public function logIn()
{
$sql = "SELECT...;"
$login = parent::builder($sql);
//vardump($login);
$data = $login->fetch(PDO::FETCH_ASSOC);
if ($login->rowCount() == 1) {
$_SESSION['id'] = $data['id'];
Redirect::to('index.php');
} else {
echo "Incorrect user and pass . . .";
exit();
}
}
this is my child constructor
public function __construct(array $args = [])
{
$this->username = $args['username'] ?? '';
$this->email = $args['email'] ?? '';
$this->phone_number = $args['phone_number'] ?? '';
$this->password = $args['password'] ?? '';
$this->photo = $args['photo'] ?? '';
$this->gender = $args['gender'] ?? '';
}
when I var dump $login I get an error ((Uncaught Error: Call to a member function prepare() on null)) how can I fix this problem?

undefined Index Conn . I am Accessing object from one file to another file

<?php
require_once("../include/connClass.php");
// $conn = new mysqli("localhost", "root", "", "hrms");
$db = new dbObj();
// var_dump($db);
$connString = $db->getConnstring();
// var_dump($connString);
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$objDesignationMaster = new DesignationMaster($connString);
switch($action) {
case 'add':
$objDesignationMaster->insertDesignationMaster($params);
break;
case 'edit':
$objDesignationMaster->updateDesignationMaster($params);
break;
case 'delete':
$objDesignationMaster->deleteDesignationMaster($params);
break;
default:
$objDesignationMaster->getDesignationMaster($params);
return;
}
class DesignationMaster {
protected $conn;
protected $data = array();
function __construct($connString) {
$this->conn = $connString;
}
// public function getDesignationMaster($params) {
// $this->data = $this->getRecords($params);
// echo json_encode($this->data);
// }
function insertDesignationMaster($params){
$data = array();
$sql = "INSERT INTO department_master (dm_department)
VALUES(
'" . $params["txtDepartment"] . "'); ";
// echo $sql;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
function getDesignationMaster($params){
}
function deleteDesignationMaster($params){
}
function updateDesignationMaster($params){
}
}
?>
I am Getting Error on this code I am Including Connection File From another file any idea about this. the object is created successfully connection object is not.
And here is my connection class
<?php
Class dbObj{
var $servername = "localhost";
var $username = "root";
var $password = "";
var $db = "hrms";
var $conn;
Public function getConnstring() {
// Create connection
$con = new mysqli($this->servername, $this->username, $this->password,
$this->db);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
} else {
$this->conn = $con;
}
return $this->conn;
}
}
?>
Use
if($this->conn->query($sql) === TRUE){ //$conn is not defined
}
$this->conn contains the connection itself. You defined it in the construct function

Empty query result in new file

I write script login php oop.
I created file Db.php method runQuery:
function runQuery($query) {
$this->last_query_result = $this->conn->query($query);
if (!$this->last_query_result) {
$this->setError("Nie udalo sie wykonac zapytania: " . $this->conn->error);
}
}
And in file login.php i created new method loginUser:
public function loginUser($login, $pass) {
$this->result = parent::runQuery("SELECT * FROM users WHERE name = '" . $login . "' AND pass='" . $pass . "'");
var_dump($this->result);
}
The problem is that the query returns NULL.
The entire file db.php
class DbUser {
private $conn;
private $host;
private $user;
private $pass;
private $base;
private $last_query_result;
function __construct($host, $user, $pass, $base) {
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->base = $base;
$this->connect();
}
public function setError($error) {
throw new Exception($error);
}
protected function connect() {
$this->conn = #new mysqli($this->host, $this->user, $this->pass, $this->base);
if ($this->conn->connect_errno) {
$this->setError("Nie udalo sie polaczyc z baza danych: " . $this->conn->connect_error);
}
}
function runQuery($query) {
$this->last_query_result = $this->conn->query($query);
if (!$this->last_query_result) {
$this->setError("Nie udalo sie wykonac zapytania: " . $this->conn->error);
}
}
function fullList() {
$return = array();
while (($row = mysqli_fetch_assoc($this->last_query_result)) !== NULL) {
$return[] = $row;
}
return $return;
}
}
And file login.php
//kalsa logowania uzytkownika
include 'db.php';
class login extends DbUser {
private $login;
private $pass;
private $result;
function __construct() {
parent::__construct('localhost', 'michal', 'saba9811', 'test');
}
public function loginUser($login, $pass) {
$this->result = parent::runQuery("SELECT * FROM users WHERE name = '" . $login . "' AND pass='" . $pass . "'");
var_dump($this->result);
}
}
try {
$login = $_POST['login'];
$pass = $_POST['pass'];
$log = new login();
$log->loginUser($login, $pass);
} catch (Exception $e) {
echo $e->getMessage();
}
Your runQuery()function doesn't return anything -
function runQuery($query) {
$this->last_query_result = $this->conn->query($query);
if (!$this->last_query_result) {
$this->setError("Nie udalo sie wykonac zapytania: " . $this->conn->error);
}
}
So when you try to assign the return value to another variable, it has nothing to assign:
$this->result = parent::runQuery("SELECT * FROM users WHERE name = '" . $login . "' AND pass='" . $pass . "'");
Fetch your query results from $this->last_query_result or refactor your code. Or just have runQuery() return $this->last_query_result, but that's a bit redundant.

Call to a member function query() on null with PDO

I just checked all of the answers are available on stackoverflow,they are similar but not my answer exactly. So please don't take this post as duplicate.
these are my codes when I'm executing it say's
Fatal error: Call to a member function query() on null in
C:\wamp64\www\ourCMS\index.php on line 12
Here is my snippet :
<?php
class DB
{
private $dbHost;
private $dbName;
private $dbUser;
private $dbPass;
protected $con;
function set_db($host, $db, $user, $pass)
{
$this->dbHost = $host;
$this->dbName = $db;
$this->dbUser = $user;
$this->dbPass = $pass;
}
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
}
}
// here is the place where i'm trying to use this actually
if (isset($_POST['submit']))
{
include('include/database.php');
$database = new DB;
$database->set_db("localhost", "ourcms", "root", "");
$conn = $database->connect();
$name = $_POST['nm'];
$query = "INSERT INTO testingpdo (name) VALUES ('$name')";
$data = $conn->query($query);
$result = $data->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
You don't return nothing from DB::connect ($conn = $database->connect();). Add return $this->con; at the end of the function.
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
return $this->con;
}

OOP database connect/disconnect class

I have just started learning the concept of Object oriented programming and have put together a class for connecting to a database, selecting database and closing the database connection. So far everything seems to work out okay except closing the connection to the database.
class Database {
private $host, $username, $password;
public function __construct($ihost, $iusername, $ipassword){
$this->host = $ihost;
$this->username = $iusername;
$this->password = $ipassword;
}
public function connectdb(){
mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
echo 'successfully connected to database<br />';
}
public function select($database){
mysql_select_db($database)
OR die("There was a problem selecting the database.");
echo 'successfully selected database<br />';
}
public function disconnectdb(){
mysql_close($this->connectdb())
OR die("There was a problem disconnecting from the database.");
}
}
$database = new database('localhost', 'root', 'usbw');
$database->connectdb();
$database->select('msm');
$database->disconnectdb();
When I attempt to disconnect from the database I get the following error message:
Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in F:\Programs\webserver\root\oop\oop.php on line 53
I'm guessing it isn't as simple as placing the connectdb method within the parenthesis of the mysql_close function but can't find the right way to do it.
Thanks
I would add a connection/link variable to your class, and use a destructor.
That will also save you from haveing to remember to close your connection, cause it's done automatically.
It is the $this->link that you need to pass to your mysql_close().
class Database {
private $link;
private $host, $username, $password, $database;
public function __construct($host, $username, $password, $database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->link = mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
mysql_select_db($this->database, $this->link)
OR die("There was a problem selecting the database.");
return true;
}
public function query($query) {
$result = mysql_query($query);
if (!$result) die('Invalid query: ' . mysql_error());
return $result;
}
public function __destruct() {
mysql_close($this->link)
OR die("There was a problem disconnecting from the database.");
}
}
Example Usage:
<?php
$db = new Database("localhost", "username", "password", "testDatabase");
$result = $db->query("SELECT * FROM students");
while ($row = mysql_fetch_assoc($result)) {
echo "First Name: " . $row['firstname'] ."<br />";
echo "Last Name: " . $row['lastname'] ."<br />";
echo "Address: " . $row['address'] ."<br />";
echo "Age: " . $row['age'] ."<br />";
echo "<hr />";
}
?>
Edit:
So people can actually use the class, I added the missing properties/methods.
The next step would be to expand on the query method, to include protection against injection, and any other helper functions.
I made the following changes:
Added the missing private properties
Added __construct($host, $username, $password, $database)
Merged connectdb() and select() into __construct() saving an extra two lines of code.
Added query($query)
Example Usage
Please if I made a typo or mistake, leave a constructive comment, so I can fix it for others.
edit 23/06/2018
As pointed out mysql is quite outdated and as this question still receives regular visits I thought I'd post an updated solution.
class Database {
private $mysqli;
private $host, $username, $password, $database;
/**
* Creates the mysql connection.
* Kills the script on connection or database errors.
*
* #param string $host
* #param string $username
* #param string $password
* #param string $database
* #return boolean
*/
public function __construct($host, $username, $password, $database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->mysqli = new mysqli($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$this->mysqli->select_db($this->database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return true;
}
/**
* Prints the currently selected database.
*/
public function print_database_name()
{
/* return name of current default database */
if ($result = $this->mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Selected database is %s.\n", $row[0]);
$result->close();
}
}
/**
* On error returns an array with the error code.
* On success returns an array with multiple mysql data.
*
* #param string $query
* #return array
*/
public function query($query) {
/* array returned, includes a success boolean */
$return = array();
if(!$result = $this->mysqli->query($query))
{
$return['success'] = false;
$return['error'] = $this->mysqli->error;
return $return;
}
$return['success'] = true;
$return['affected_rows'] = $this->mysqli->affected_rows;
$return['insert_id'] = $this->mysqli->insert_id;
if(0 == $this->mysqli->insert_id)
{
$return['count'] = $result->num_rows;
$return['rows'] = array();
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$return['rows'][] = $row;
}
/* free result set */
$result->close();
}
return $return;
}
/**
* Automatically closes the mysql connection
* at the end of the program.
*/
public function __destruct() {
$this->mysqli->close()
OR die("There was a problem disconnecting from the database.");
}
}
Example usage:
<?php
$db = new Database("localhost", "username", "password", "testDatabase");
$result = $db->query("SELECT * FROM students");
if(true == $result['success'])
{
echo "Number of rows: " . $result['count'] ."<br />";
foreach($result['rows'] as $row)
{
echo "First Name: " . $row['firstname'] ."<br />";
echo "Last Name: " . $row['lastname'] ."<br />";
echo "Address: " . $row['address'] ."<br />";
echo "Age: " . $row['age'] ."<br />";
echo "<hr />";
}
}
if(false == $result['success'])
{
echo "An error has occurred: " . $result['error'] ."<br />";
}
?>
you're not returning anything from connectdb() yet you're passing this function's return to mysql_close().
You should be aware that mysql_* functions were introduced in PHP 4, which is more then 1 yours ago. This API is extremely old, and the process has begun to actually deprecating this extension.
You should not in 2012 write new code with mysql_* functions.
There exist two very good alternative : PDO and MySQLi. Both of which are already written with object oriented code in mind, and they also give you ability to use prepared statements.
That example you showed in the original post written with PDO would look like this:
//connect to the the database
$connection = new PDO('mysql:host=localhost;dbname=msm', 'username', 'password');
//disconnects
$connection = null;
Of course there are more complicated use-case, but the point stand - time to evolve.
mysql_close requires a parameter to disconnect but you are providing nothing.
class Database {
private $host, $username, $password, $con;
public function __construct($ihost, $iusername, $ipassword){
$this->host = $ihost;
$this->username = $iusername;
$this->password = $ipassword;
$this->con = false;
}
public function connect() {
$connect = mysql_connect($this->host, $this->username, $this->password);
return $connect;
}
public function connectdb(){
$conn = $this->connect();
if($conn)
{
$this->con = true;
echo "Successsfully Connected. ";
return true;
}
else {
echo "Sorry Could Not Connect. ";
return false;
}
}
public function select($database){
if($this->con)
{
if(mysql_select_db($database))
{
echo "Successfully Connected Database. $database. ";
return true;
}
else
{
echo "Unknown database. ";
}
}
else {
echo "No active Connection. ";
return false;
}
}
public function disconnectdb(){
if($this->con)
{
if(mysql_close($this->connect()))
{
$this->con = false;
echo "Successfully disconnected. ";
return true;
}
}
else
{
echo "Could Not disconnect. ";
return false;
}
}
}
$database = new database('localhost', 'root', '');
$database->connectdb();
$database->select('databaseoffacebook');
$database->disconnectdb();
Object Oriented Programming works well with PDO and mysqli. Give it a try
<?php
class Database{
private $link;
//private $host,$username,$password,$database;
//private $status;
public function __construct(){
$this->host = 'localhost';
$this->username = 'root';
$this->password = '';
$this->database = 'workclass';
$this->link = mysqli_connect($this->host,$this->username,$this->password);
$this->status = mysqli_select_db($this->link,$this->database);
if (!$this->status) {
return $this->status="Failed to Connected with Database";
}else{
return $this->status="Database is connected";
}
}
}
$object = new Database();
echo $object->status;
?>

Categories