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?
Related
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);
I want to create a script that runs any query from through PHP the same way you would run it through the MySQL console just by calling MySQL::query([the query]);.
I have created a good portion of the PHP script already but I think I'm stuck. So far it can pull information just fine but it does not like it when I try to make any changes to the database itself. I would like it to also write to MySQL as well, but I can't figure out how to do it dynamically.
Here is the code I have so far:
<?php
include '..\..\shared\Error_Code.php';
class MySQL {
private static $host;
private static $username;
private static $password;
private static $database;
private static $logged_in = false;
public static function login($host, $username, $password, $database) {
self::$host = $host;
self::$username = $username;
self::$password = $password;
self::$database = $database;
if (self::confirm_login()) {
self::$logged_in = true;
} else {
self::$logged_in = false;
Error_Code::print(107.0); //There was an issue with the login.
}
}
public static function change_database($database) {
if (self::$logged_in) {
$old_database = self::$database;
self::$database = $database;
if (!self::confirm_login()) {
self::$database = $database;
Error_Code::print(107.1); //The database you entered dose not exist.
}
} else {
Error_Code::print(107.2); //You have not logged in yet.
}
}
private static function confirm_login($host = -1, $username = -1, $password = -1, $database = -1) {
$host = (($host != -1) ? $host : self::$host);
$username = (($username != -1) ? $username : self::$username);
$password = (($password != -1) ? $password : self::$password);
$database = (($database != -1) ? $database : self::$database);
if (!(is_null(self::$host) || is_null(self::$username) || is_null(self::$password) || is_null(self::$database))) {
$connection = mysqli_connect($host, $username, $password);
if ($connection) {
$response = mysqli_query($connection, "SHOW DATABASES");
$bg_db = array("information_schema", "mysql", "performance_schema", "phpmyadmin", "test");
if (!in_array(self::$database, $bg_db)) {
while ($row = mysqli_fetch_assoc($response)) {
if($row['Database'] == self::$database) {
return true;
}
}
}
Error_Code::print(107.8); //Login information is wrong.
return false;
} else {
Error_Code::print(107.9); //Login information is wrong.
return false;
}
} else {
Error_Code::print(107.7); //Login information is missing.
return false;
}
}
public static function logged_in() {
return self::$logged_in;
}
public static function query($query, $host = -1, $username = -1, $password = -1, $database = -1) {
$host = (($host != -1) ? $host : self::$host);
$username = (($username != -1) ? $username : self::$username);
$password = (($password != -1) ? $password : self::$password);
$database = (($database != -1) ? $database : self::$database);
$continue = self::confirm_login($host, $username, $password, $database);
if ($continue) {
return new Data($query, $host, $username, $password, $database);
} else {
return new Data($query, $host, $username, $password, $database);
Error_Code::print(107.3); //You have not logged into a database.
}
}
}
class Data {
private $query;
private $host;
private $username;
private $password;
private $database;
public function __construct($query, $host, $username, $password, $database) {
if ($query < 0) {
return $this;
} else {
$this->query = $query;
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
return $this->get();
}
}
//get data from a database using an SQL query
public function get() {
//query database
$connection = mysqli_connect($this->host, $this->username, $this->password, $this->database);
if ($connection) {
$response = mysqli_query($connection, $this->query);
//get data from query
if ($response) {
$rows = array();
while ($row = mysqli_fetch_array($response, MYSQLI_ASSOC)) {
array_push($rows, $row);
}
return $rows;
} else {
if (true) {
//<----- I THINK THIS IS WHERE I WOULD HAVE TO ADD THE CODE FOR MAKING CHANGES TO THE DATABASE
//$prepare = mysqli_prepare($connection, $this->query);
//mysqli_stmt_execute($prepare);
} else {
Error_Code::print(108.0); //Could not run query because there was no response
return -1;
}
}
} else {
Error_Code::print(108.1); //Could not run query because there was no connection
return -1;
}
}
//print the results of the query to a table
public function print_table($table_id = -1) {
$data = $this->get();
if ($data < 0) {
Error_Code::print(108.2); //Could not build table do to an issue with the query.
return -1;
} else {
$th = "<tr>";
foreach ($data[0] as $col => $value) {
$th = "$th<th>$col</th>";
}
$th = "$th</tr>";
$td = "";
foreach ($data as $row) {
$td = "$td<tr>";
foreach ($row as $col => $value) {
$td = "$td<td>$value</td>";
}
$td = "$td</tr>";
}
$table_id = ($table_id < 0) ? "" : " id='$table_id'";
echo "<table class='database_data'$table_id>$th$td</table>";
return 1;
}
}
}
?>
Any ideas on what I can change to get it to INSERT, DELETE, UPDATE and everything else.
Check this out:
https://github.com/indieteq/indieteq-php-my-sql-pdo-database-class
It might be a bit too much for your needs, but is, in my opinion, a great example of how to build a database class
i have php class USER and Database class im doing 10000 users app, and that user will be query 3-4 times a day minumum . my class base and function base here them looking yet for thats have any problem ? or need any fix ?
MY db class
class Database
{
private $host = "";
private $db_name = "";
private $username = "";
private $password = "";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
print'{"success": "0","message": "Service Error, Please try again later "}';
}
return $this->conn;
}
}
Also my USER class here
<?php
require_once('dbconfig.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID)
{
try
{
$stmt2 = $this->conn->prepare("UPDATE Products SET productCode='$code',productName='$name',productDescription='$description',specialWarning='$specialwarning',productQuantity='$quantity',productPrice='$price' WHERE ID=$productID");
$stmt2->execute();
echo'{"success": "1", "message": "Product Updated"}';
return true;
}
catch(PDOException $e)
{
}
$this->conn = null; // HERE I DID NULL FOR DISABLE MAX CONNECTIONS
}
}
AND HER MY updateproduct.php
<?php
header('Content-type: application/json');
$name = $_REQUEST['name'];
$code = $_REQUEST['code'];
$description = $_REQUEST['description'];
$quantity = $_REQUEST['quantity'];
$price = $_REQUEST['price'];
$specialwarning = $_REQUEST['specialwarning'];
$productID = $_REQUEST['productID'];
include_once 'class.user.php';
$user = new USER($DB_con);
if($user->updateProduct($name,$code,$description,$quantity,$price,$specialwarning,$productID))
{
}
else
{
}
?>
Can you check my codes is good class for big users ? and good connection returns ? Can i add something ? or need any fix ?Also need to close class ?
Thanks
I cannot see anything when on my xampp server and displays an empty page. I am trying to find the error but failed. anyone can help would be appreciated
here is class.db.php
<?php
class db {
private $conn;
private $host;
private $user;
private $password;
private $baseName;
private $port;
private $Debug;
function __construct($params=array()) {
$this->conn = false;
$this->host = 'localhost'; //hostname
$this->user = 'root'; //username
$this->password = ''; //password
$this->baseName = 'db'; //name of your database
$this->debug = true;
$this->connect();
}
function __destruct() {
$this->disconnect();
}
function connect() {
if (!$this->conn) {
try {
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->baseName.'', $this->user, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
if (!$this->conn) {
$this->status_fatal = true;
echo 'Connection BDD failed';
die();
}
else {
$this->status_fatal = false;
}
}
return $this->conn;
}
function disconnect() {
if ($this->conn) {
$this->conn = null;
}
}
function getOne($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetch();
return $reponse;
}
function getAll($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetchAll();
return $reponse;
}
function execute($query) {
if (!$response = $this->conn->exec($query)) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
return $response;
}
}
and index.php has at the top above <!doctype
<?PHP
include('db.class.php');
$bdd = new db();
?>
along my html code
You just created an instance of this class, this only triggered the constructor, you did not make any calls to functions, so nothing shows on that page.
For the future: enable displaying errors by adding
ini_set('display_errors',1);
this will help you to find and correct errors.
this class work with mysql perfect
but i wanted to connect now with mssql server
so when i try to change mysql to mssql i get error
"Fatal error: Call to a member function prepare() on a non-object"
<?php
class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct() {
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array (
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$this->dbh = new PDO ($dsn, $this->user, $this->pass, $options);
} // Catch any errors
catch ( PDOException $e ) {
$this->error = $e->getMessage();
}
}
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null) {
if (is_null ( $type )) {
switch (true) {
case is_int ( $value ) :
$type = PDO::PARAM_INT;
break;
case is_bool ( $value ) :
$type = PDO::PARAM_BOOL;
break;
case is_null ( $value ) :
$type = PDO::PARAM_NULL;
break;
default :
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue ( $param, $value, $type );
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_OBJ);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_OBJ);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
}
any idea thank You
It looks like you need to use the MSSQL specific prepare function. Just using the example from the page but you can substitute your code.
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
i found the solution
here is the constractor using dblib
public function __construct() {
$hostname = "";
$port = ;
$dbname = "";
$username = "";
$pw = "";
// Set DSN
$dsn = 'sqlsrv:Server=' . $this->host . ';Database=' . $this->dbname;
// Set options
$options = array (
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$this->dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
} // Catch any errors
catch ( PDOException $e ) {
$this->error = $e->getMessage();
}
}