I have a class that I am passing a query to, but the fatal error
function query on null'
occurs when attempting to run the query.
I echoed $mysql_statement and got
select * from users
which is the intended query, but in the context of the query statement it keeps telling returning the fatal error function query on null.
Any ideas on why the "select * from users" that is legitimately stored in $mysql_statement is being interpreted as null? (the properties used and not defined here are defined in a parent class):
The page.php:
<?php
include("includes/database_classes.php");
new database_connection;
new database_query("SELECT * FROM users");
?>
...and the database_classes.php:
<?php
/*----------------------------------------------------------------------------------------------------*/
class database_connection
{
protected $username = 'root';
protected $password = '';
protected $hostname = 'localhost';
protected $database = 'assistant';
protected $database_handle;
function connect()
{
try
{
$database_handle = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
}
catch (PDOException $e)
{
print "Error!: " . $e ->getMessage() . "<br/>";
die();
}
}
}
/*----------------------------------------------------------------------------------------------------*/
class database_disconnection extends database_connection
{
function disconnect()
{
$database_handle = null;
}
}
/*----------------------------------------------------------------------------------------------------*/
class database_query extends database_connection
{
protected $mysql_statement;
function __construct( $mysql_statement )
{
$this->mysql_statement = $mysql_statement;
echo $mysql_statement;
foreach($this->database_handle->query("$mysql_statement")->fetch_assoc() as $row) {
print_r($row);
}
}
}
/*----------------------------------------------------------------------------------------------------*/
I think you are having problem when trying to loop through the result of your SQL query, this happened because, you didn't include method "fetch_assoc()"
Instead of:
foreach($this->database_handle->query("$mysql_statement") as $row);
Why not?
foreach($this->database_handle->query("$mysql_statement")->fetch_assoc() as $row)
Related
I wanna get data on table and write a class. But this class doesn't work because pdo doesn't access. How can I get table data with this class?
$db = new PDO("mysql:host=localhost;dbname=xxx;charset=utf8", "xxx", "xxx");
class uye extends PDO{
var $id;
var $kadi;
function cek($id){
$query = $db->query("SELECT * FROM btc WHERE id='{$id}'", PDO::FETCH_ASSOC);
if ( $query->rowCount() ) {
foreach( $query as $row ){
$this->id=$row["id"];
$this->kadi=$row["kadi"];
}
}
}
}
$bilgiler=new uye;
$bilgiler->cek(1);
echo $bilgiler->kadi;
So I'm running this off of fetching all data as I dont know where you're getting $id from.
I generally break my code up into files and folders as I found this easier to work with and others to work on.
// database connection file (dbc.php)
class Database
{
private $host = "127.0.0.1";
private $db = "";
private $user = "";
private $password = "";
public $conn;
public function dbConnect()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db, $this->user, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
I then make a common file, this is where you can store all of your frequently used functions or your static functions
// Common file (common.php)
require_once('dbc.php');
class DBCommon
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnect();
$this->conn = $db;
}
public function run($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
So to explain this a little more, you will see a function of run() this is just to save the tedious $this->conn->prepare on every query.. Now you can run $this->run()
The next would be your class file.. this is where your logic goes:
// your class file... (class.btc.php)
require_once "common.php";
class BTC extends DBCommon
{
public function getQuery()
{
$stmt = $this->run("SELECT * FROM `btc`");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_OBJ))
{
$rows[] = $row;
}
return $rows;
}
}
Self explanatory..
And then your calling method.. Lets say index.php
// File you're calling your class from (index.php)
require_once "class.btc.php";
$fetch = new BTC();
$returnData = $fetch->getQuery();
foreach ($returnData as $data)
{
echo
"<p>$data->something</p>
<p>$data->somethingElse</p>";
}
It seems a little long winded I know, but the time you'll save overall will help!
I'm attempting to create a mysql query using OOP in PHP. In the code below the class "database_disconnection" does not toss any errors or notices, however the last class "database_query" gives me a notice that $database_handle is undefined. I have no idea what's causing this as I created the database_query class as a derivative class of database_connection, which include the $database_handle variable as private. Any help would be greatly appreciated!
Instantiating the objects:
include("includes/database_classes.php");
new database_connection;
new database_query('SELECT * FROM users');
and the classes:
<?php
/*----------------------------------------------------------------------------------------------------*/
class database_connection
{
private $username = 'root';
private $password = '';
private $hostname = 'localhost';
private $database = 'assistant';
private $database_handle;
function connect()
{
try
{
$database_handle = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
}
catch (PDOException $e)
{
print "Error!: " . $e ->getMessage() . "<br/>";
die();
}
}
}
/*----------------------------------------------------------------------------------------------------*/
class database_disconnection extends database_connection
{
function disconnect()
{
$database_handle = null;
}
}
/*----------------------------------------------------------------------------------------------------*/
class database_query extends database_connection
{
private $mysql_statement;
function __construct( $mysql_statement )
{
$this->mysql_statement = $mysql_statement;
foreach($database_handle->query("$mysql_statement") as $row) {
print_r($row);
}
}
}
/*----------------------------------------------------------------------------------------------------*/
?>
In your database_query constructor, you're attempting to use $database_handle before initializing it. If you notice, you only initialize in the connect function of your parent class (database_connection).
Either call connect before trying to refer to it, or initialize it in the parent's constructor, and call it (parent::__construct();).
I'm currently creating a really simplistic online ordering website as part of a school project. I am running into an issue where my controller tries to create an instance of a class that interfaces with my order parameters, but creating the new instance simply returns NULL. When the page where the operation is called loads, I receive this error:
Fatal error: Call to a member function getParameters() on null in /home/data/www/z1785732/public_html/467/PlaceOrderController.php on line 31
Here are the files I'm working with:
This is the controller. The specific class that is returning NULL is ParameterInterface.
<?php
include 'ItemDB.php';
include 'OrderDB.php';
include 'ccInterface.php';
include 'ParameterInterface.php';
class PlaceOrderController {
var $itemDB;
var $parameter;
var $orderDB;
var $ccInterface;
function __construct() {
$this->itemDB = new ItemDatabase();
$this->ccInterface = new ccInterface();
$this->parameter = new ParameterInterface();
}
public function displayCatalog() {
return $this->itemDB->displayCatalog();
}
public function searchItem($itemNum) {
return $this->itemDB->searchItem($itemNum);
}
public function getParameters() {
return $this->parameter->getParameters();
}
public function addOrder() {
$this->orderDB->addOrder($array1, $array2);
}
public function ccAuthorize($ccInfo) {
return $this->ccInterface->ccAuthorize($ccInfo);
}
}
?>
Here is ParameterInterface.php, where the function is defined.
<?php
class ParameterInterface {
function connect() {
$servername = '';
$dbname='';
$username = '';
$password = '';
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Connection failed: ". $e->getMessage();
}
return $conn;
}
public function getParameters() {
$conn = $this->connect();
$query = "SELECT * FROM Admin;";
$result = $conn->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
return $row;
}
}
?>
I'm hoping it's just something simple that my eyes aren't catching. Any help would be greatly appreciated.
Thanks in advance!
Implement the Serializable interface to be able to serialize your controller in session:
class PlaceOrderController implements Serializable
{
// ...
public function serialize()
{
return serialize(array(
$this->itemDB,
$this->parameter,
$this->orderDB,
$this->ccInterface
));
}
public function unserialize($serialized)
{
list(
$this->itemDB,
$this->parameter,
$this->orderDB,
$this->ccInterface
) = unserialize($serialized);
}
// ...
}
Remember to start a new session after you do this. (clear your cookie) You may using an old PlaceOrderController object, with no propriety, in your current session.
Also, you may want rethink about this whole script. This isn't Java. Why you want store PlaceOrderController in session?
Your code seems clean enough to me... however; depending on the version of PHP you are using, the var Keyword might not be ideal here since it means Public. If your Member Variables are Public; getters and setters are really more or less not that necessary as such.
Back to the Issue. I would suggest taking a look at the name of the File: ParameterInterface.php because it may not have been properly included which might be a Typo or so in the Filename. Be mindful of cases (Upper & Lower - depending on your Operating System). Try first checking if the file exist to see what you get; like so:
<?php
if(file_exist("ParameterInterface.php")){
include "ParameterInterface.php";
die ("Sure, ParameterInterface.php exists and it has been included...");
}else{
die("Ah haaaa! Gotcha!!! So, 'ParameterInterface.php' does not exist in the current Directory....");
}
//AFTER THIS QUIRK DEBUGGING... YOU MIGHT JUST KNOW MORE...
Would You mind to try redefining your Class, instead? Like so:
<?php
class ParameterInterface {
/**
* #var PDO $CON_LINK
*/
protected static $CON_LINK;
//WOULDN'T HURT TO ADD AN EMPTY CONSTRUCTOR... NOW, WOULD IT?
function __construct(){
$servername = '';
$dbname = '';
$username = '';
$password = '';
if(!self::$CON_LINK) {
try {
self::$CON_LINK = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
self::$CON_LINK->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
}
function connect() {
return self::$CON_LINK;
}
public function getParameters() {
$conn = $this->connect();
$query = "SELECT * FROM Admin;";
$result = $conn->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
return $row;
}
}
?>
Hope this helps a little...
Here's our class so far:
class DB {
private $DBUser = 'xxx';
private $DBPass = 'xxx';
private $DBServer = 'xxx';
private $DBName = 'xxx';
public $sql;
public $id;
public function __construct($sql,$id){
$this->sql = $sql;
$this->id = $id;
} //end variables
public function select() {
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);
/*return $conn;*/
$stmt = $conn->prepare($this->sql);
$id = $this->id;
$stmt->execute(array('id'=>$id));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
} //end method
} //end class
We call it using this:
$db = new DB;
$result = $db->select('SELECT * FROM tbl_xxx WHERE myid = :id',$_GET['id']);
But I'm getting the following error:
Warning: Missing argument 1 for DB::__construct() Warning: Missing
argument 2 for DB::__construct()
I'm sure the answer is a simple one, but I can't see it. What am I missing here??
I usually extend the PDO class like
class DB extends PDO {...}
Then make sure your constructor calls the parent (PDO) one with the connection string. However, once I needed to connect to the database using a separate function. This was doing:
// Establish the connection.
try {
$this->str="";
switch ($this->proto){
case "mysql":
$this->str = "mysql:host=$this->host;dbname=$this->db";
break;
default:
throw new PDOException("Wrong protocol '$proto'");
}
parent::__construct($this->str,
$this->user, $this->pw,$opts);
}catch (PDOException $e) {
$this->last_error = $e->getMessage();
error_log($e->getMessage());
return false;
}
Also, make sure though that you do not connect every time you select! So probably you should make separate select and connect functions. Finally, instead of select, delete, etc functions I usually make a generic/base (but a bit unsafe) member which will return any query results:
public function send_query($query){
$result = $this->query($query);
if ($result === false){
$this->last_error = $this->errorInfo();
return false;
}
$ret = $result->fetchAll();
$result->closeCursor();
return $ret;
}
The above is "unsafe" because anything in $query string is going to run on the database. Wrapper functions should ensure that the string is properly escaped and contains no malicious code. I would suggest that you use prepared statements for all your queries but the above method should do what you ask.
I'm a beginner in PHP. I'm trying to get data from database but I'm having the following error
"Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\phpExamPrep\studentDB.php on line 22"
I'm sorry I have to include all the codes, its just to help you help me. Thanks
I have the following classes
class database
{
private static $dsn = 'mysql:local=localhost;dbname=test1';
private static $username ='me';
private static $password ='me';
public static $db;
private function __construct()
{
}
public static function dataConnect()
{
if(isset(self::$db))
{
try
{
self::$db = new PDO(self::$dsn, self::$username, self::$password);
}
catch(PDOException $e)
{
$error_message = $e->getMessage();
include 'database_error.php';
exit();
}
}
return self::$db;
}
}
class studentDB
{
public static function getAllRecords()
{
require 'database.php';
$query = 'select * from student';
$db = database::dataConnect();
$result = $db->query($query); //This part is giving error
$students = array();
foreach($result as $row)
{
$stud = new student($row['firstname'],$row['lastname']);
$stud->setID($row['id']);
$students[]=$stud;
}
return $students;
}
}
<?php
include 'studentDB.php';
$stx =studentDB::getAllRecords();
foreach ($stx as $r)
{
echo $r->getFirstName().' '.$r->getLastName().' '.$r->getID();
}
?>
when I changed if(isset(self::$db)) to if(!isset(self::$db)), the error becomes
"Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\phpExamPrep\studentDB.php on line 25"
I think this
if(isset(self::$db))
must be changed in
if ( ! isset(self::$db) )
as you want to set self::$db if it's not set already and not the opposite.
From the code fragment that you posted in fact, it looks like this call
$db = database::dataConnect();
is returning a null reference to $db and therefore you cannot call query on a null reference.