Fatal error: Uncaught Error ( php mysql ) - php

I am learning php oop with mysql and I am having trouble fixing this code.
I have checked it twice and also checked this platform to confirm.
<?php
require 'databasesclass.php';
$database = new Database();
$database->query('SELECT * FROM users');
$rows = $database->resultset();
print_r($rows);
and my data base class are
<?php
class Database{
private $host = 'localhost:8889';
private $user = 'root';
private $pass = 'root';
private $dbname = 'register';
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set the DSN
$dsn = 'mysql:host='. $this->host . ';dbname=' . $this->dbname . $this->user . $this->pass;
// set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($pram, $value, $type = null){
if (is_null($type)){
switch(true) {
case is_int($value):
$type = PDO::PRAM_INT;
break;
case is_bool($value):
$type = PDO::PRAM_BOOL;
break;
case is_null($value):
$type = PDO::PRAM_NULL;
break;
default:
$type = PDO::PRAM_STR;
}
}
$this->stmt->bindValue($parm, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchALL(PDO::FETCH_ASSOC);
}
}
Fatal error: Uncaught Error: Call to a member function prepare() on
null in C:\MAMP\htdocs\Practice\databasesclass.php:31 Stack trace: #0
C:\MAMP\htdocs\Practice\index.php(7): Database->query('SELECT * FROM
u...') #1 {main} thrown in C:\MAMP\htdocs\Practice\databasesclass.php
on line 31
And the Line 31 is:
$this->stmt = $this->dbh->prepare($query);

No need to pass $this->user and $this->pass into your $dns variable. Remove them from there.
So $dns variable will be
from
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . $this->user . $this->pass;
to
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
Please check and let me if you see any error there.

In the moment that you are executing the $database->query('SELECT * FROM users') the $this->dbh is null. You could check if it is an instance of PDO before do the prepare.

Related

PHP Code not selecting from database

UPDATE: There was no issue with the code used in counting. There was just a typo error in connecting to database
$this->conn = new PDO("mysql:host=". $this->host . ";db_name=" . $this->db_name, $this->username, $this->password);
the db_name should be dbname. So its something like
$this->conn = new PDO("mysql:host=". $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
I am try a PHP REST api with mysql database but this doesn't seem to be working as i have tried to select from my database as the first step but this returns no result despite there being a record in the database
Below are my codes
database.php
<?php
class Database
{
//Database Credentials
private $host = "localhost";
private $username = "root";
private $password = "password";
private $db_name = "rtmdb";
public $conn;
//Get Database Connection
public function getConnection()
{
$this->conn = null;
//Try connection
try
{
$this->conn = new PDO("mysql:host=". $this->host . ";db_name=" . $this->db_name, $this->username, $this->password);
$this->conn->exec("set names utf8");
}
catch(PDOException $exception)
{
echo "Connection error:" . $exception->getMessage();
}
return $this->conn;
}
}
admin.php to select from database
<?php
class Admin
{
//Database Connection and Table name
private $conn;
private $table_name = "admin";
//object properties
public $id;
public $fname;
public $lname;
public $oname;
public $uname;
public $email;
public $idnumber;
public $password;
public $profimage;
public $datecreated;
public $modifiedby;
public $datemodified;
public $status;
//Construct $db as database connection
public function __construct($db)
{
$this->conn = $db;
}
public function crawl()
{
$query = "SELECT * FROM " . $this->table_name;
$stmt = $this->conn->prepare($query);
$stmt->execute();
return $stmt;
}
}
crawl.php file to get data and json_encode results
//Include database and object files
include_once "../config/database.php";
include_once "../objects/admin.php";
$database = new Database();
$db = $database->getConnection();
$admin = new Admin($db);
//Query Admin
$stmt = $admin->crawl();
$num = $stmt->rowCount();
echo json_encode($num);
if($num > 0)
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$admin_list = array(
"id" => $id,
"uname" => $uname
);
array_push($admin_arr['records'], $admin_list);
}
echo json_encode($admin_arr);
}
else
{
echo json_encode(
array("message" => "No registered admin found.")
);
}
But i get rowCount() as 0 and "no registered admin" despite having records
Below are screenshots of my table structures
the database structure
I also have only one data in the database
But these seem to give me no result. Please what the issue and how do i fix?

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

Php class inside connection close or class close?

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

how i can convert this class to work with mssql

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

class undefined property in php

maybe this is a possible duplicate, i have search here some questions like this but i have tried all the answers, but i still got this error
Notice: Undefined property: User::$_pdo in D:\xampp\htdocs\pengun\classes\DB.php on line 32
and this error
Fatal error: Call to a member function prepare() on a non-object in D:\xampp\htdocs\pengun\classes\DB.php on line 32
this is my DB class
<?php
class DB {
private $_pdo, $_query, $_result, $_count, $_row;
public function __construct($host, $dbname, $user, $password) {
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->dbname = $dbname;
try {
$_pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->dbname, $this->user, $this->password);
} catch (PDOException $e) {
die($e->getMessage());
}
$_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function select($fields, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=','>','<','>=','<=');
$column = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "SELECT {$fields} FROM {$table} WHERE {$column} {$operator} {$value}";
if($this->_query = $this->_pdo->prepare($sql)) {
$this->_query->execute();
$this->_row = $this->_query->fetch();
print_r($this->_row);
}
}
}
}
}
can someone please tell me what is the problem with my code? thanks in advance.
Because in constructor, you are assigning new PDO just to local variable accessible only inside constructor. You have to use:
$this->_pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->dbname, $this->user, $this->password);
...
$this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
You are assigned PDO object to local variable in constructor. You must set class variable!
Change
$_pdo
to
$this->_pdo
in lines 13 and 18.

Categories