I am writing a query class for my php project, But i have a problem the query does not return any values from my DB.
PHP code:
<?php
class DatabaseConnect{
protected $host = 'localhost';
protected $user = 'root';
protected $pass = 'root';
protected $db = 'test';
public function __construct(){
$con = mysqli_connect($this->host, $this->user, $this->pass, $this->db) or die('Cannot Connect to DB');
return $con;
}
}
class ExecuteQuery{
public $connection;
public $result;
public function __construct(){
$this->connection = new DatabaseConnect();
}
public function getQueryAction($sql){
$this->result = mysqli_query($this->connection, $sql);
}
public function setStringAction($string){
$file = file_get_contents('queryFile.json');
$json = json_decode($file, true);
foreach($json['Queries'] as $this->result){
return $this->result[$string];
}
}
}
$execute = new ExecuteQuery();
Jason file ('it will contain all the queries') :
{
"Queries": [
{"query1":"SELECT * FROM tbl_user"},
{"query2":"SELECT * FROM tbl_users WHERE status=1"}
]
}
Index file:
<?php
require_once('query.php');
?>
<html>
<head>
<title>
</title>
</head>
<body>
<h1>Welcome</h1>
<h3><?php
$execute->getQueryAction($execute->setStringAction('query1'));
foreach($execute->result as $item){
echo $item['id']. ' ' . $item['user_name'] .'<br />';
}
?></h3>
</body>
</html>
So what I do is create a class to process jason file extract a query and then class to run a query. Jason file as I mentioned holds all the queries, In index and in any file where I include query.php i can run all the queries like this:
$execute->getQueryAction($execute->setStringAction('query name'));
after some debugging I realised that the code fails in getQueryAction method, I think mysqli_query dont like $this->connection.
My questions are :
Why
and how to fix it
A constructor cannot return anything, a constructor only purpose is to create an instance of a class
private $con;
public function __construct(){
$this->con = mysqli_connect($this->host, $this->user, $this->pass, $this->db)
or die('Cannot Connect to DB');
}
public function get_connection(){
return $this->con;
}
so in ExecuteQuery class you can do:
public function __construct(){
$db = new DatabaseConnect();
$this->connection = $db->get_connection();
}
mysqli->query does not return results. It only returns a handle with which you could request the results. Look up mysqli->fetch_assoc
http://php.net/manual/en/mysqli-result.fetch-assoc.php
if ($result = mysqli_query($this->connection, $sql)) {
/* fetch associative array */
while ($item = mysqli_fetch_array($result)) {
echo $item['id']. ' ' . $item['user_name'] .'<br />';
}
/* free result set */
mysqli_free_result($result);
}
Thx for trying to help me guys, But I just managed to fixe it with minor changes here they are:
changed the method namd from __construct to DBcon under DatabaseConnection class,
then i did this in get getQueryAction:
$this->result = mysqli_query($this->connection->DBcon(), $sql);
the whole class:
class DatabaseConnect{
protected $host = 'localhost';
protected $user = 'root';
protected $pass = 'root';
protected $db = 'test';
public function DBcon(){
$con = mysqli_connect($this->host, $this->user, $this->pass, $this->db) or die('Cannot Connect to DB');
return $con;
}
}
class ExecuteQuery{
public $connection;
public $result;
public function __construct(){
$this->connection = new DatabaseConnect();
}
public function getQueryAction($sql){
$this->result = mysqli_query($this->connection->DBcon(), $sql);
}
public function setStringAction($string){
$file = file_get_contents('queryFile.json');
$json = json_decode($file, true);
foreach($json['Queries'] as $this->result){
return $this->result[$string];
}
}
}
$execute = new ExecuteQuery();
Now everything works perfect still not sure why the previous method (present in inital question) but this works xD
Related
Here is my config.php
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'xxxx');
define('DB_USER', 'xxxx');
define('DB_PASS', 'xxxx');
?>
And It is DB.php
<?php
include 'config.php';
class DB {
public static $pdo;
public static function connection(){
if (!isset(self::$pdo)) {
try {
self::$pdo = new PDO('mysql:host='.DB_HOST.'; dbname ='.DB_NAME,DB_USER, DB_PASS);
}catch(PDOException $e){
echo $e->getMessage();
}
}
return self::$pdo;
}
public static function prepareOwn($sql){
return self::connection()->prepare($sql);
}
}
?>
3rd file is Student.php
<?php
include 'DB.php';
class Student {
public $table = 'student_info';
public function readAll(){
$sql = "SELECT * FROM $this->table";
$stmt = DB::prepareOwn($sql);
$stmt->execute();
return $stmt->fetchAll();
}
}
?>
But When I try to access readAll() from index.php using spl_autoload_register() Then I can see Fatal error: Call to undefined method DB::prepareOwn()
Can anyone help me to solve the problem??
Many thanks.
Sahidul
i copied your code into mine and saw your error. but as i guessed, first you will get an error with this line inside db.php:
return self::$pdo->prepare($sql);
Fatal error: Call to a member function prepare() on null
where prepare function came from? $pdo is just a static property in this class and it doesn't have a function called prepare! fix this line
Updated
the problem is you forgot to call connection method inside your prepareOwn. so your new prepareOwn function should be:
public static function prepareOwn($sql) {
self::connection();
return self::$pdo->prepare($sql);
}
i hope this code will work for you
class MySQLDatabase {
// Class attributes
private $host_name = "localhost";
private $database_name = "XXXXXXX";
private $database_username = "XXXXXXX";
private $database_password = "XXXXXXX";
private $is_connected;
private $connection;
private $statement ;
// construct
public function __construct() {
$this->open_connection();
}// End of construct
// connection method
public function open_connection() {
try {
$this->is_connected = TRUE ;
// PDO Connection
$this->connection = new PDO("mysql:host=".$this->host_name.";dbname=".$this->database_name.";charset=utf8",$this->database_username,$this->database_password);
// Error reporting
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES,FALSE);
} catch(PDOException $errors) {
$this->is_connected = FALSE ;
self::catch_errors($errors);
}
}// End of open connection method
// Get connection method
public function connection(){
return $this->connection ;
}
// Close connection method
public function close_connection() {
$this->connection = null;
}// End of close connection method
private static function catch_errors($errors) {
echo("<h4><p>" . $errors -> getMessage() . "</p></h4>");
die();
}
// query method
public function query($sql){
return $this->statement = $this->connection->prepare($sql);
}
}// End of database class
$database = new MySQLDatabase();
class Student {
protected static $table = 'My_table';
public function readAll(){
global $database;
try{
$sql = "SELECT * FROM ". self::$table;
$stmt = $database->query($sql);
$stmt->execute();
return $stmt;
}catch(PDOException $error){
echo("<h4><p>" . $errors -> getMessage() . "</p></h4>");
die();
}
}
}
$c = new Student();
$s = $c->readAll();
$stmt = $s->fetchAll(PDO::FETCH_ASSOC);
foreach($s as $v){
var_dump($v);
}
so recently I've been trying to use more procedural mysqli for practise, and have been looking at http://www.phpknowhow.com/mysql/mysqli-procedural-functions/, and also w3schools as reference, but i'm still having trouble so I thought I'd ask.
I have this database.php file where I have alot of stuff but the important stuff is
class Database{
public $host = DB_HOST;
public $username = DB_USER;
public $password = DB_PASS;
public $db_name = DB_NAME;
public $link;
public $error;
public function __construct(){
$this -> connect();
}
private function connect(){
$link = mysqli_connect($this->host,$this->username,$this->password,$this->db_name);
if(!$link){
echo "Failed".mysqli_error($link);
}
}
// create select method
public function select($query){
$result = mysqli_query($link,$query) or die("didnt work".mysqli_error($link));
if(mysqli_num_rows($result) > 0){
return $result;
}
else{
return false;
}
}
Now the way it currently works fine in my index.php file is simply by doing something like
$db = new Database();
//CREATe query
$query = "SELECT * FROM posts";
$posts = $db->select($query);
Is there any way to implement $posts = $db->select($query) with procedural functions? Before I have done stuff like mysqli_query($link,$query), but link is public here and inside a class so I can't do that, plus I want to access the function select . Thanks!
$link is not defined in your function select.
Modify your connect function:
private function connect() {
$this->link = mysqli_connect($this->host, $this->username, $this->password, $this->db_name);
if(!$this->link) {
echo "Failed: " . mysqli_error($this->link);
}
}
Now $this->link may be used in your select function:
public function select($query){
$result = mysqli_query($this->link, $query) or die("didn't work: " .mysqli_error($this->link));
if(mysqli_num_rows($result) > 0) {
return $result;
}
else{
return false;
}
}
I suggest you read the PHP OOP documenentation (at least the first chapters) to get a better understanding.
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.
I'm very new to php constructors I know of from java. But for some reason, this one is not running. I am following a tutorial and I can't seem to get a 1 only a 0. Here are the two scripts involved:
<?php
class dbConnection{
protected $db_conn;
public $db_name = 'todo';
public $db_user = 'root';
public $db_pass = '';
public $db_host = 'localhost';
function connect(){
try{
$this->db_conn = new PDO("mysql:host=$this->db_host;db_name=$this->db_name",$this->db_user,$this->db_pass);
return $this->db_conn;
}
catch(PDOException $e)
{
return $e->getMessage();
}
}
}
?>
<?php
include_once( 'class.database.php' );
class ManageUsers {
public $link;
public $constructed;
function ManageUsers(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link;
}
function registerUser($username,$password,$ip_address,$time,$date){
$query = $this->link->prepare("INSERT INTO users (username,password,ip_address,time,date) VALUES (?,?,?,?,?)");
$values = array($username,$password,$ip_address,$time,$date);
$query->execute($values);
$counts = $query->rowCount();
return $counts;
}
}
$users = new ManageUsers();
echo $users->registerUser('bob','bob','127.0.0.1','10:00','29-02-2012');
?>
You should try to use __construct() instead for ManageUsers().
Also, I'm not quite sure what you're trying to achieve in your constructor (see my markings below):
function ManageUsers(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link; //<--?
$constructed = 'Construct'; //<--?
}
Agreed - the method you are using is the old school PHP4 method - you should use the __construct() method as explained above.
http://www.php.net/manual/en/language.oop5.decon.php
This page explains construct() & destruct() in PHP 5
// constructor
function __construct() {
ManageUsers();
}
function ManageUsers(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
$constructed = 'Construct';
}
You cannot return from a constructor tho, maybe you can want to make link a public property and access it directly like this
$user = new ManageUsers();
$link = $user->$link;