I've been using this class:
<?
class DbConnector {
var $theQuery;
var $link;
function DbConnector() {
$host = 'localhost';
$db = 'my_db';
$user = 'root';
$pass = 'password';
// connect to the db
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
function find($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return array();
$retArray = array();
while ($row = mysql_fetch_array($ret))
$retArray[] = $row;
return $retArray;
}
function insert($query) {
$ret = mysql_query($query, $this->link);
if (mysql_affected_rows() < 1)
return false;
return true;
}
function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
// get some results
function fetchArray($result) {
return mysql_fetch_array($result);
}
function close() {
mysql_close($this->link);
}
function exists($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return false;
}
function last_id($query) {
return mysql_insert_id($query);
}
}
?>
Which I'm using for a lot of queries and it's working fine, although I'm trying to insert using this query:
global $db;
$query = $db->insert("INSERT INTO `submissions` (
`id` ,
`quote` ,
`filename` ,
`date_added` ,
`uploaded_ip`
)
VALUES (
NULL , '{$quote}', '{$filename}', NOW(), '{$_SERVER['REMOTE_ADDR']}')
");
And it's giving me this error:
Not Found
The requested URL /horh_new/id/<br /><b>Fatal error</b>: Call to a member function insert() on a non-object in <b>/Applications/MAMP/htdocs/horh_new/addit.php</b> on line <b>52</b><br /> was not found on this server.
Although when I don't use that class above, and use this instead:
$con = mysql_connect("localhost","root","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO `submissions` (
`id` ,
`quote` ,
`filename` ,
`date_added` ,
`uploaded_ip`
)
VALUES (
NULL , '{$quote}', '{$filename}', NOW(), '{$_SERVER['REMOTE_ADDR']}')
");
echo mysql_insert_id();
mysql_close($con);
It works fine. Can anyone tell me what is wrong with my class? I'd really appreciate it.
You should do like
global $db;
$db = new DbConnector();
Or the better way to use this is
add a static function of class DbConnector, which will create only single instance throughout a request
public static function getInstance(){
static $instance = null;
if($instance === null){
$instance = new DbConnector();
}
return $instance;
}
And use this class as
$db = DbConnector::getInstance();
$db->insert($query);
you need to instantiate the object before using it
$db = new DbConnetor();
now you can do an insert
although i suggest adding a __construct method to connect to the database first
class DbConnector {
public function __construct() {
// connect to db here
}
Are you sure $db contains an instance of your class? Maybe just do a var_dump() of $db just before your call to $db->insert() and see if it's set.
Related
Good morning.
I'm trying to make a DB class to connect and retrieve results from my DB. So, I think with the class is everything good. But, the results won't appear.
Here is my DB class:
<?php class Conexao {
var $host = "localhost";
var $usuario = "root";
var $senha = "xxxxxx";
var $banco = 'restaurante';
private $mysqli;
public function Abrir()
{
$this->mysqli = new mysqli($this->host, $this->usuario, $this->senha, $this->banco);
}
public function Fechar()
{
$this->mysqli->close();
}
}
class Comando {
public function Executar($sql)
{
$con = new Conexao();
$con->Abrir();
$re = $con->mysqli->query($sql);
$con->Fechar();
return $re;
}
}
?>
And here is where I'm trying to retrieve the results:
<?php
$queryMesasAtivas = Comando::Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"');
if ($queryMesasAtivas->num_rows > 0) {
while ($rowMesasAtivas = $queryMesasAtivas->fetch_assoc()) {
echo "<option value='".$rowMesasAtivas['numero']."'>Mesa ".$rowMesasAtivas['numero']."</option>";
}
}
else {
echo '<option>Nenhuma mesa ativa</option>';
}
?>
I tried some modifications but, nothing changes. Everytime it's still not working. What's wrong?
As the Comando::Executar is not static, but rather declared as public function..., you will have to do something such as:
$comando = new Comando();
$queryMesasAtivas = $comando->Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"');
if ($queryMesasAtivas->num_rows > 0) {
while ($rowMesasAtivas = $queryMesasAtivas->fetch_assoc()) {
echo "<option value='".$rowMesasAtivas['numero']."'>Mesa ".$rowMesasAtivas['numero']."</option>";
}
}
else {
echo '<option>Nenhuma mesa ativa</option>';
}
Or declare the method as static, namely:
public static function Executar($sql)
{
$con = new Conexao();
$con->Abrir();
$re = $con->mysqli->query($sql);
$con->Fechar();
return $re;
}
And then you can use the double colon (::) syntax:
$queryMesasAtivas = Comando::Executar('SELECT * FROM mesas WHERE status =1 AND numero !="'.$_SESSION["mesa"].'"');
I would suggest not calling an open and close every time you run a query, but rather a class like this:
class Conexao
{
private $link;
public function __construct($host = null, $username = null, $password = null, $dbName = null)
{
$this->link = mysqli_init();
$this->link->real_connect($host, $username, $password, $dbName) or die("Failed to connect");
}
public function __destruct()
{
$this->link->close();
}
public function Query($sql)
{
return $this->link->query($sql);
}
}
This is then used as such:
$conexao = new Conexao("host", "username", "password", "db_name");
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
This is not only smaller, but more lightweight on the server because you aren't permanently opening and closing database connections, reducing CPU use and memory use.
Using static properties for the host etc. (keeps them in memory even after __destruct is used so you do not need to redeclare them every time):
class Conexao
{
private $link;
private static $host, $username, $password, $dbName;
public function __construct($host = null, $username = null, $password = null, $dbName = null)
{
static::$host = $host ? $host : static::$host;
static::$username = $username ? $username : static::$username;
static::$password = $password ? $password : sattic::$password;
static::$dbName = $dbName : $dbName : static::$dbName;
$this->link = mysqli_init();
$this->link->real_connect(static::$host, static::$username, static::$password, static::$dbName) or die("Failed to connect");
}
public function __destruct()
{
$this->link->close();
}
public function Query($sql)
{
return $this->link->query($sql);
}
}
$conexao = new Conexao("host", "username", "password", "db_name");
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
$conexao->__destruct(); // Destroy the class
$conexao = new Conexao(); // Reinitialise it
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
Using a config instance of the connection class:
config.php file:
<?php
require_once 'path/to/Conexao.php';
$conexao = new Conexao("host", "username", "password", "db_name");
?>
index.php file:
<?php
require_once 'config.php';
$result = $conexao->Query("SELECT * FROM `table` WHERE 1 ORDER BY `id` ASC;");
?>
The class now has a parent on my github!
This is my code in config.php file:
<?php
$db_username = 'name';
$db_password = 'my password';
$db_name = 'my db';
$db_host = 'localhost';
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if ($mysqli->connect_error) {
throw new Exception("Error in Database Connection!");
}
?>
Now I have separate function.php with class commonFunctions
<?php
require_once '../config/config.php';
class commonFunctions {
function doLogin(){
global $mysqli;
$result = $mysqli->query("SELECT * FROM table WHERE itemcolor = 'red'") ;
$row_cnt = $result->num_rows;
return $row_cnt;
}
}
$common=new commonFunctions();
?>
Here I am using global $mysqli; to access $mysqli from config, which may not be a appropriate way to program and using global $mysqli; in every function to access $mysqli looks so bad.
Can you guys pls suggest better and clean way.
Thanks
It depends what programming paradigm you're comfortable with. Personally I like my PHP to be Object Orientated (OO), so i'd put the mysql in a new class called DB or something and then when I want to run the query i'd do $db->query('blabla').
class DB {
private $db;
function __construct() {
$dbConfig = Main::app()->config['db'];
$this->db = new \mysqli($dbConfig['host'], $dbConfig['user'], $dbConfig['pass'], $dbConfig['db']);
}
public function query($query, $where = false) {
if (!empty($where)) {
if (strpos(strtolower($where), 'where') > 0)
$query .= ' ' . $where;
else
$query .= ' WHERE ' . $where;
}
$result = $this->db->query($query);
if (!isset($result) || $result === false) {
dd([$query, $this->db->error, $where]);
}
/* will return true on INSERT / UPDATE queries */
if ($result !== true)
return $result->fetch_all(MYSQL_ASSOC);
}
}
Maybe you might just want to create a function in commonFunctions that handled all queries?
function query($query) {
global $mysqli;
return $mysqli->query($query);;
}
I am making a module in which I am fetching users from Database Using OOP.
But due to some reason , records are not fetching, and there is no mysql error.
Here is my Code:
dbsetup_class.php :
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
/* echo "<pre>";
var_dump($this->dbc);
*/
//echo $sql;
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
And here is my index.php:
<?php
require_once("dbsetup_class.php");
$connection = new mySQL();
$connection->connect('localhost', 'admin', 'admin', 'oop_test');
//die('success');
$myquery = "SELECT * FROM users";
$query = $connection->query($myquery);
$array = $connection->fetch($query);
while($array)
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
What I am doing here?
Your fetch method expects SQL query, and not the result of a query. You should redefine it as (assuming that the client code is what you want as an interface):
public function fetch($resource)
{
$array = mysqli_fetch_array($resource);
return $array;
}
Also if you have results, your while will be infinite.
This question already has an answer here:
php error Call to a member function query() on a non-object [closed]
(1 answer)
Closed 9 years ago.
i have this class for connect to MySql database and create/insert user but when work with this i see error.
My Auth Class is:
class AuthDB {
private $db;
public function __construct() {
$db = new Dbaccess();
if (!$db->connect ( DB_SERVER, DB_USER, DB_PASS, DB_NAME ) ) {
if (mysql_error() == '')
$database_incorrect = 'Database name is incorrect or doesn\'t exist';
else
$database_incorrect = 'ERROR: ';
echo $database_incorrect . mysql_error ();
}
}
public function createUser($email, $password, $salt, $verification) {
$ver = 0;
$act = 1;
$adm = 0;
$MYSQLDB = "INSERT INTO tbUsers (email, password, user_salt, is_verified, is_active, is_admin, verification_code) "
. "VALUES ('1', '1', '1', '1', '1', '1', '1')"; //test value
$r2 = $db->query ($MYSQLDB) or error ('Critical Error', mysql_error () ); // <<<LINE 30 ERROR HERE
if ($r2 > 0) {
return true;
}
return false;
}
}
My Dbaccess class Is:
class Dbaccess
{
var $q_array = array();
var $db_id;
var $query;
var $counter = 0;
var $timecounter = 0;
var $query_res;
function connect ($host, $login, $password, $db)
{
$this->host = $host;
$this->login = $login;
$this->password = $password;
$this->db = $db;
$this->db_id = #mysql_connect($this->host, $this->login, $this->password);
if ($this->db_id)
{
$db_select = #mysql_select_db($this->db);
$this->query("SET NAMES 'UTF8'");
if (!$db_select)
{
#mysql_close($this->db_id);
$this->db_id = $db_select;
}
else
return $this->db_id;
}
else
return false;
}
function close()
{
if($this->db_id)
{
if($this->query)
{
#mysql_free_result($this->query);
}
$result = #mysql_close($this->db_id);
return $result;
}
else {
return false;
}}
function query ($query)
//
// $db->query("QUERY");
{
unset($this->query_res);
if($query != "")
{
$sql_start = explode(' ', microtime());
$this->query_res = #mysql_query($query, $this->db_id);
$sql_stop = explode(' ', microtime());
$sql_time = $sql_stop[0] - $sql_start[0];
$sql_time+= $sql_stop[1] - $sql_start[1];
$this->timecounter+= round($sql_time, 5);
$this->counter++;
}
if($this->query_res)
{
unset($this->q_array[$this->query_res]);
return $this->query_res;
}
else
{
return false;
}
}
}
Now i see this error when send data :
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\test\classes\Auth.php on line 30
How to Fix This Error? Where is my mistake?
You want this in your __construct:
public function __construct() {
$this->db = new Dbaccess();
And when you query, you want:
$this->db->query($MYSQLDB);
When you just use the variable $db, it only exists within the scope of that method. But when you use class properties it exists within the scope of the entire class.
After taking some advice from people on here in a previous thread, I'm trying to convert my MySQL to PDO, but am running into some issues.
Here is my original MySQL connection class:
class DbConnector {
public static function getInstance() {
static $instance = null;
if ($instance === null) {
$instance = new DbConnector();
}
return $instance;
}
protected $theQuery;
private $link;
function DbConnector() {
$host = 'localhost';
$db = '';
$user = '';
$pass = '';
// connect to the db
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
public function find($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return array();
$retArray = array();
while ($row = mysql_fetch_array($ret))
$retArray[] = $row;
return $retArray;
}
public function insert($query) {
$ret = mysql_query($query, $this->link);
if (mysql_affected_rows() < 1)
return false;
return true;
}
public function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
public function fetchArray($result) {
return mysql_fetch_array($result);
}
public function close() {
mysql_close($this->link);
}
public function exists($query) {
$ret = mysql_query($query, $this->link);
if (mysql_num_rows($ret) == 0)
return false;
}
public function last_id($query) {
return mysql_insert_id($query);
}
}
Here is the function that I'm writing:
function getRandomSubmission() {
global $db;
if(!empty($_GET['id'])){
$submission_id = $_GET['id'];
$query = $db->find("
SELECT
*
FROM
`submissions`
WHERE id = '{$submission_id}'
LIMIT 1
");
}
else {
$query = $db->find("
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
");
}
if($query) {
return $query[0];
}
else {
$query = $db->find("
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
");
}
}
Here is the PDO connector:
$host = 'localhost';
$username = '';
$pass = '';
$db = '';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $username, $pass);
} catch (PDOException $e) {
echo $e->getMessage();
}
Here is what I've tried to convert it to, but it's just plain wrong. I think I need to be returning a PDO associative array in the 2nd if statement, but am not sure.
function getRandomSubmission() {
global $dbh;
if(!empty($_GET['id'])){
$submission_id = $_GET['id'];
$stmt = $dbh->prepare('
SELECT
*
FROM
`submissions`
WHERE
`id` = ?
LIMIT 1
');
$stmt->bindParam(1, $submission_id, PDO::PARAM_INT);
$stmt->execute();
}
else {
$stmt = $dbh->prepare('
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
');
$stmt->execute();
}
if($stmt) {
return $stmt[0];
}
else {
$stmt = $dbh->prepare('
SELECT
*
FROM
`submissions`
ORDER BY RAND()
LIMIT 1
');
$stmt->execute();
}
}
The original one works as intended, however (I realize I left the connection details blank).
You need to call fetch method of the PDOStatement object:
return $stmt->fetch()
Read about the fetch style, really you don't need FETCH_BOTH ;-)