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;
}
Related
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.
While trying to connect through PHP it displays
Warning: mysqli_connect(): (HY000/1044): Access denied for user ''#'localhost' to database 'bookedscheduler' in C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php on line 52
Warning: mysqli_select_db() expects parameter 1 to be mysqli, boolean given in C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php on line 53
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, boolean given in C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php on line 54
Cannot modify header information - headers already sent by (output started at C:\wamp\www\booked\lib\Database\MySQL\MySqlConnection.php:53) in C:\wamp\www\booked\Pages\Page.php on line 138
My config.php
database connection
$conf['settings']['database']['type'] = 'mysql';
$conf['settings']['database']['user'] = 'booked_user';
$conf['settings']['database']['password'] = '';
$conf['settings']['database']['hostspec'] = '127.0.0.1';
$conf['settings']['database']['name'] = 'bookedscheduler';
Mysqlconnection.php file
class MySqlConnection implements IDbConnection
{
private $_dbUser = '';
private $_dbPassword = '';
private $_hostSpec = '';
private $_dbName = '';
private $_db = null;
private $_connected = false;
/**
* #param string $dbUser
* #param string $dbPassword
* #param string $hostSpec
* #param string $dbName
*/
public function __construct($dbUser, $dbPassword, $hostSpec, $dbName)
{
$this->_dbUser = $dbUser;
$this->_dbPassword = $dbPassword;
$this->_hostSpec = $hostSpec;
$this->_dbName = $dbName;
}
public function Connect()
{
if ($this->_connected && !is_null($this->_db))
{
return;
}
$this->_db = mysqli_connect($this->_hostSpec, $this->_dbUser, $this->_dbPassword,$this->_dbName);
$selected = mysqli_select_db($this->_db, $this->_dbName);
mysqli_set_charset($this->_db, 'utf8');
if (!$this->_db || !$selected)
{
throw new Exception("Error connecting to database\nError: " . mysql_error());
Log::Error("Error connecting to database\n%s", mysql_error());
}
$this->_connected = true;
}
public function Disconnect()
{
mysqli_close($this->_db);
$this->_db = null;
$this->_connected = false;
}
public function Query(ISqlCommand $sqlCommand)
{
mysqli_set_charset($this->_db, 'utf8');
$mysqlCommand = new MySqlCommandAdapter($sqlCommand, $this->_db);
Log::Sql('MySql Query: ' . str_replace('%', '%%', $mysqlCommand->GetQuery()));
$result = mysqli_query($this->_db, $mysqlCommand->GetQuery());
$this->_handleError($result);
return new MySqlReader($result);
}
public function LimitQuery(ISqlCommand $command, $limit, $offset = 0)
{
return $this->Query(new MySqlLimitCommand($command, $limit, $offset));
}
public function Execute(ISqlCommand $sqlCommand)
{
mysqli_set_charset($this->_db, 'utf8');
$mysqlCommand = new MySqlCommandAdapter($sqlCommand, $this->_db);
Log::Sql('MySql Execute: ' . str_replace('%', '%%', $mysqlCommand->GetQuery()));
$result = mysqli_query($this->_db, $mysqlCommand->GetQuery());
$this->_handleError($result);
}
public function GetLastInsertId()
{
return mysqli_insert_id($this->_db);
}
private function _handleError($result, $sqlCommand = null)
{
if (!$result)
{
if ($sqlCommand != null)
{
echo $sqlCommand->GetQuery();
}
throw new Exception('There was an error executing your query\n' . mysql_error());
Log::Error("Error executing MySQL query %s", mysql_error());
}
return false;
}
}
class MySqlLimitCommand extends SqlCommand
{
/**
* #var \ISqlCommand
*/
private $baseCommand;
private $limit;
private $offset;
public function __construct(ISqlCommand $baseCommand, $limit, $offset)
{
parent::__construct();
$this->baseCommand = $baseCommand;
$this->limit = $limit;
$this->offset = $offset;
$this->Parameters = $baseCommand->Parameters;
}
public function GetQuery()
{
return $this->baseCommand->GetQuery() . sprintf(" LIMIT %s OFFSET %s", $this->limit, $this->offset);
}
}
?>
Please someone guide me in this regard
It is very easy and I am providing you a tested answer, first you need to build the Database class as seen below, you need to put it in a file and include it from your homepage (might be the index.php page). Then, you need to initiate an instance of your class from the homepage to connect to the database, the code is very well explained in details in this great article: www.muwakaba.com/php-database-connection
<?php
// Class definition
class Database{
// The constructor function
public function __construct(){
// The properties
$this->host = "your_DB_host_address";
$this->login = "your_DB_login_name";
$this->password = "your_DB_password";
$this->name = "your_DB_name";
// The methods
$this->connect();
$this->select();
}
// The connect function
private function connect(){
$this->connection = mysql_connect($this->host, $this->login, $this->password) or die("Sorry! Cannot connect to the database");
}
// The select function
private function select(){
mysql_select_db($this->name, $this->connection);
}
}
?>
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
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 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.