I have error in my code:
Fatal error: Call to a member function query() on a non-object in /var/www/crud_php/core/class_ManageDatabase.php on line 23
Error line: $query = $this->link->query("SELECT * FROM $table_name ORDER BY id ASC");
<?php
class ManageDb{
public $link;
function __construct() {
include_once 'class_database.php';
$conn = new database;
$this->link = $conn->connect();
return $this->link;
}
function getData($table_name, $id=null){
if(isset($id)){
$query = $this->link->query("SELECT * FROM $table_name WHERE id = '$id' ORDER BY id ASC");
}else{
**$query = $this->link->query("SELECT * FROM $table_name ORDER BY id ASC");**
}
$rowCount = $query->rowCount();
if ($rowCount >=1){
$result = $query->fetchAll();
}else{
$result = 0;
}
return $result;
}
}
?>
db connect:
<?php
include_once '../config.php';
class database {
protected $db_conn;
public $db_name = DB_NAME;
public $db_host = DB_HOST;
public $db_pass = DB_PASS;
public $db_user = DB_USER;
function connect() {
try {
$this->db_conn = new PDO("mysql:host = $this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
} catch (PDOException $e) {
return $e->getMessage();
}
}
}
?>
It means $this->link is not an object. You forgot to return the connection in your connect() method. Add return $this->db_conn; in that method.
On a side-note, returning a string in case of an error is a very bad idea. Let the exception propagate or terminate the script - but not return something completely else that will cause odd errors later in your code.
You also cannot return anything from a constructor.
Related
I am a newbie in PHP programming. I have created a config and a script which prints all my MySQL database information. Here is my config :
class DbManager{
protected $dbh;
public $dbhost = '127.0.0.1';
public $dbname = 'bookstore';
public $dbuser = 'root';
public $dbpass = '';
public function getConnection(){
try{
$dbh = new PDO("mysql:host=$this->dbhost;dbname=$this->dbname", $this->dbuser,
$this->dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
catch(PDOException $e){
echo "Error : " . $e;
}
}
}
and, this is my script to get my database information :
require_once('config.php');
class ShowData extends DbManager{
public function getInfo(){
$dbh= getConnection();
$smt = $dbh->prepare("SELECT * FROM books");
$smt->execute();
$result = $smt->fetchAll();
echo "<pre>";
print_r($result);
}
}
I am getting the error : Fatal error: Uncaught Error: Call to undefined function getConnection().
I am not able to make a connection variable by which I can make my SQL queries. I have my suspicions about $dbh= getConnection(). Am I making the queries alright?
Your getConnection is in class so you need to call like $this->getConnection()
class ShowData extends DbManager{
public function getInfo(){
$dbh= $this->getConnection(); // change this line
$smt = $dbh->prepare("SELECT * FROM books");
$smt->execute();
$result = $smt->fetchAll();
echo "<pre>";
print_r($result);
}
}
I'm getting this error in my PHP file.
My login function
<?php
session_start();
include ("../dbConnection.php");
class login {
public $link;
function __construct()
{
$dbc = new dbConnection();
$this->link = $dbc->Connect();
return $this->link;
}
public function get_data($emailid,$password)
{
$q = $this->link->prepare("SELECT id from students WHERE emailid='$emailid' AND password='$password' AND active='Yes'");
$q->execute(array(':emailid'=>$emailid,':password'=>$password));
$counts = $q->fetch();
if($counts['id'] > 0)
{
session_start();
$_SESSION['userlogin'] = $counts['id'];
$encrypt_id1 = $this->encrypt_decrypt('encrypt', $counts['id']);
echo $encrypt_id1;
}
}
}
dbConnection.php
<?php
public class dbConnection {
public $conn;
public $db_host = 'localhost';
public $db_name = 'pte_mock';
public $db_user = 'root';
public $db_pass = '';
public function Connect()
{
try{
$this->conn = new PDO("mysql:host=".$this->db_host.";dbname=".$this->db_name,$this->db_user,$this->db_pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
return $this->conn;
}
}
I'm getting error with below statement
"$q = $this->link->prepare("SELECT id from students WHERE emailid='$emailid' AND password='$password' AND active='Yes'");"
Error
"PHP Fatal error: Uncaught Error: Call to a member function prepare() on null"
I don't know whats the issue with this.If anyone knows solution please help me to get out of this issue.Thanks in advance.
When you define a class you do need a constructor in order to initialize instance variables.
class dbConnection {
public $conn,
$db_host,
$db_name,
$db_user,
$db_pass;
public function __construct()
{
$this->conn = false;
$this->db_host = 'localhost';
$this->db_name = 'pte_mock';
$this->db_user = 'root';
$this->db_pass = '';
}
/* ... */
Also a class cannot be defined public, that should raise a syntax error at compile time.
So you just have class dbConnection {
I'm not sure this is leading to problems but construstors must not return values. In fact they return the instance (object) just created.
You have into the class login:
function __construct()
{
$dbc = new dbConnection();
$this->link = $dbc->Connect();
// return $this->link; // <--- REMOVE THAT - YOU CANNOT RETURN VALUES HERE!
}
When you call $lgn = new login() the function __construct() is invoked and you get into $lgn a new instance of the class login. If the constructor returns anything that is discarded!
So you should refactor your code this way:
$lgn = new login(); // <--- returns a new instance of the class login
$the_link= $lgn->link; // <--- this way you access `link` instance variable
Finally this
$q = $this->link->prepare("SELECT id from students WHERE emailid='$emailid' AND password='$password' AND active='Yes'");
Is not the proper way to build a prepared statement as you're injecting values into the query instead of specifying placeholders.
The line should be written this way
$q = $this->link->prepare("SELECT id from students WHERE emailid=:$emailid AND password=:password AND active='Yes'");
replace this part of your code
$q = $this->link->prepare("SELECT id from students WHERE emailid='$emailid' AND password='$password' AND active='Yes'");
$q->execute(array(':emailid'=>$emailid,':password'=>$password));
with this:
$q = $this->link->prepare("SELECT id FROM students WHERE emailid = :emailid AND password = :password AND active = 'Yes'");
$q->execute(array(':emailid'=>$emailid,':password'=>$password));
i have created an OOP-PHP Script and i get follow Message and i don't understand why???
Fatal error: Call to undefined method ConnectDatabase::query() in .... on line 73
My PHP Code
<?php
class ConnectDatabase {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'database';
private $db_connection;
private $db_query;
//Connect Database.
function __construct() {
$this->open_db();
}
public function query($sql) {
$this->db_query = query($sql, $this->db_connection);
}
public function open_db() {
$this->db_connection = new mysqli($this->host, $this->username, $this->password);
if (is_resource($this->db_connection)) {
die("Error!");
} else {
$this->db_connection->select_db($this->database) or die('Error');
}
}
}
$dbConnection = new ConnectDatabase();
class GetContent {
public function newContent() {
global $dbConnection;
$sql = "SELECT * FROM mytable";
// ----- This Line make an Error ------
$query = $dbConnection->query($sql);
$found = $dbConnection->fetch_array($query);
return $found;
}
}
If you have any Idea please help.
I have a sequence order of PHP programming that i need to query from a table and insert it in a JSON array. I dont know where my mistake is but it just doesnt go through. please help me,
in dbinfo.inc.php,
define("ORA_CON_UN", "ADMIN");
define("ORA_CON_PW", "pass");
define("ORA_CON_DB", "192.168.100.195/finance");
class db {
private $conn;
private $lastId;
private static $instance;
private function _construct(){
$this->connect();
}
public static function create(){
if (!isset(self::$instance)) {
self::$instance = new db();
}
return self::$instance;
}
public function connect($dbconn = ORA_CON_DB, $dbuser = ORA_CON_UN, $dbpass = ORA_CON_PW){
$this->conn = oci_connect($dbuser, $dbpass, $dbconn);
}
}
and in DBFunction.php
include 'dbinfo.inc.php';
class Connection{
private $dbConnection;
public function _construct($dbConnection){
$this->dbConnection = $dbConnection;
}
function initConnection(){
$db = new db();
$dbConnection = $db->connect();
}
}
class PurchaseOrder {
private $job = '%';
private $subjob = '%';
public function _construct($job, $subjob){
$this->job = $job;
$this->subjob = $subjob;
}
function listPO($job, $subjob){
$conn = new Connection();
$conn->initConnection();
$sql = oci_parse($conn, 'SELECT VPI.PO_NO FROM VW_PO_INFO#WENFINANCE_WENLOGINV_LINK WHERE VPI.PROJECT_NO = ' .$job. ' AND VPI.PROJECT_NAME = ' .$subjob);
if (!$conn) {
$oerr = OCIError($conn);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
exit();
} else {
echo 'CONNECTION SUCCEDED';
}
$rows = array();
while ($r = oci_fetch_assoc($sql)){
$rows[] = $r;
}
$listPO = json_encode($rows);
oci_execute($sql);
oci_close($conn);
}
}
and lastly, testDBFunction.php
include('DBFunction.php');
$queryOracle = new PurchaseOrder();
$queryOracle->listPO('W-IGG','');
var_dump($queryOracle);
and this is my error message,
Warning: oci_parse() expects parameter 1 to be resource, object given
in C:\xampp\htdocs\WeltesFinance\pages\lib\DBFunction.php on line 36
CONNECTION SUCCEDED Warning: oci_fetch_assoc() expects parameter 1 to
be resource, null given in
C:\xampp\htdocs\WeltesFinance\pages\lib\DBFunction.php on line 47
Warning: oci_execute() expects parameter 1 to be resource, null given
in C:\xampp\htdocs\WeltesFinance\pages\lib\DBFunction.php on line 52
object(PurchaseOrder)#1 (2) { ["job":"PurchaseOrder":private]=>
string(1) "%" ["subjob":"PurchaseOrder":private]=> string(1) "%" }
I dont know exactly where my error is, Please help me
UPDATE:
I made some more updates to your code and classes, here's relevant changes for each file.
dbinfo.inc.php
<?php
define("ORA_CON_UN", "ADMIN");
define("ORA_CON_PW", "pass");
define("ORA_CON_DB", "192.168.100.195/finance");
Class DbConnect{
private $user = null;
private $password = null;
private $db_string = null;
public function __construct(){
$this->user = ORA_CON_UN;
$this->password = ORA_CON_PW;
$this->db_string = ORA_CON_DB;
}
public function connect() {
$connection = oci_pconnect($this->user, $this->password, $this->db_string);
return $connection;
}
}
?>
DBfunction.php
<?php
include 'dbinfo.inc.php';
// there is no need for a Connection class unless you want further wrapping or something :-/
Class PurchaseOrder {
// ....
public function listPO($job,$subjob){
$db = new DbConnect();
$conn = $DbConnect->connect();
if (!$conn) {
// keep your code, throw error, exit
}
else{
// move all your database processing here
$sql = oci_parse($conn, 'SELECT VPI.PO_NO FROM VW_PO_INFO...');
// also note that you are passing an empty value for the $subjob parameter, thus making the query likely to fail
oci_execute($sql);
$rows = array();
while($r = oci_fetch_assoc($sql)){
$rows[] = $r;
}
$listPO = json_encode($rows);
oci_close($conn);
}
return $listPO; // you need to return $listPO in order to be able to dump it
}
// ....
}
testDBFunction.php
<?php
include('DBFunction.php');
$queryOracle = new PurchaseOrder();
// either pass what listPO() returns to a variable and dump it
$jsonResults = $queryOracle->listPO('W-IGG','');
var_dump($jsonResults);
// or dump the return directly
// var_dump($queryOracle->listPO('W-IGG',''));
You need to return the actual connection resource in the initConnection function
See the following inline comments
function initConnection(){
$db = new db();
// $dbConnection = $db->connect(); // this is not needed since you call connect from the
// constructor, but you need to return the connection
// see below the EDIT
// return the actual connection resource
// return $dbConnection;
return $db;
}
$sql = oci_parse($conn->initConnection(), 'SELECT VPI.PO_NO FROM VW_ ...')`
EDIT:
public function connect($dbconn = ORA_CON_DB, $dbuser = ORA_CON_UN, $dbpass = ORA_CON_PW){
$this->conn = oci_connect($dbuser, $dbpass, $dbconn);
return $this->conn;
}
today i tried to convert my code to PHP/MySQLi OOP code.
class Database
{
private $host;
private $user;
private $password;
private $db;
private $mysqli;
function __construct()
{
$this->host = "*****";
$this->user = "*****";
$this->password = "******";
$this->db = "*****";
$this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);
if (mysqli_connect_errno()):
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
endif;
}
}
This is a script for the query's:
include_once("WD_Config/database.php");
class Adressen_Db
{
function __construct()
{
$this->database = new Database();
}
public function selecteer()
{
$query = "SELECT * FROM wd_adressen WHERE verborgen = 0 ORDER BY naam ASC";
$result = $this->database->mysqli->query($query);
return $result;
}
}
And this is how i call it.
$adressen = new Adressen_Db;
$adressen_result = $adressen->selecteer();
echo "<p>";
while ($row = $adressen_result->fetch_assoc()):
echo "<a href='http://maps.google.com/?q=".$row['voladres']."' target='_blank'>".$row['naam']."</a> woonachtig op <i>".$row['voladres']."</i><br>";
endwhile;
echo "</p>";
I alway get a "Call to a member function query() on a non-object". Doesn't matter what i trie ...
Can somebody tell me why that is?
Thanks!
The $mysqli variable in class Database is declared private.
You can access it only through setters and getters.
I think while you definitely need to have $mysqli as public so it can be accessed in the other method, there might be something else, as the error would be something like
trying to access private property in database class
or something like that, whereas your script throws a non-object call error
I think your new Adressen_Db; lacks the parenthesis:
$adressen = new Adressen_Db();
You can replace your code with this:
Config.php
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "your_database_name");
Now include this file in your database file
require_once 'config.php';
Class Database {
public $host = DB_HOST;
public $user = DB_USER;
public $pass = DB_PASS;
public $dbname = DB_NAME;
public $link;
public $error;
public function __construct() {
$this->getConnection();
}
private function getConnection() {
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
if (!$this->link) {
$this->error = "Connection failed" . $this->link->connect_error;
return false;
}
}
// for only select query
public function select($query) {
$result = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($result->num_rows > 0) {
return $result;
} else {
return false;
}
}
// for insert, delete and update
public function myquery($query) {
$myquery = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($myquery) {
return $myquery;
} else {
return false;
}
}
}
Now, make your queries like this:
<?php
require_once './lib/Database.php';
?>
<?php
class Admin {
private $db;
public function __construct() {
$this->db = new Database();
}
public function getData(){
$query = "SELECT * FROM admin";
$result = $this->db->select($query);
if($result != false){
while($row = $result->fetch_assoc()){
// do your thing
}
}
}
public function insert(){
$query = "INSERT INTO admin(admin_name) VALUES('$admin_name')";
$result = $this->db->myquery($query);
if($result){
$msg = "User has been added successfully.";
return $msg;
} else {
$msg = "Error while adding user. Please try again.";
return $msg;
}
}
}
Do this.