Building from a tutorial I found online.
I m trying to select all items from the 'items' table and create an array. Not sure how this is suppose to work. This $result = $this->connection->query($q); is what is causing the problem.
<?php
//DB.class.php
class DB {
protected $db_name = 'dbname';
protected $db_user = 'user';
protected $db_pass = 'pass';
protected $db_host = 'localhost';
protected $connection;
public function connect() {
$connection = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
// check connection
if ($connection->connect_error) {
trigger_error('Database connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
}
public function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function sel($table) {
$q = "SELECT * FROM $table";
$result = $this->connection->query($q);
$rows = $this->resultToArray($result);
return $rows;
$result->free();
}
}
make a construct function like
public $mysqli;
public function __construct()
{
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$this->mysqli = $mysqli;
}
public function sel($table,$whr)
{
$query = "SELECT * FROM ".$table." where id='$whr'";
$result = $this->mysqli->query($query);
$total = array();
while($row = $result->fetch_assoc()){
//print_r($row);die;
$total[] = $row;
}//print_r($total);die;
return $total;
}
I think you should set a constructor, but if you don't want, just return an instance of it first and set your $this->connection property instead of $connection (the normal variable):
class DB {
protected $db_name = 'test';
protected $db_user = 'test';
protected $db_pass = 'test';
protected $db_host = 'localhost';
protected $connection;
public function connect() {
$this->connection = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
// ^^ this one, not $connection
// check connection
if ($this->connection->connect_error) {
trigger_error('Database connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
return $this->connection; // then return this
}
public function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function sel($table) {
$q = "SELECT * FROM $table";
$result = $this->connection->query($q);
// ^ so that if you call this, you have the mysqli object
$rows = $this->resultToArray($result);
return $rows;
$result->free();
}
}
$db = new DB(); // instantite,
$db->connect(); // then connect, shouldn't have to have this if you put the connection automatically on construct
$result = $db->sel('users'); // feed a valid existing table name
echo '<pre>';
print_r($result);
Related
how to display rows in my users table in PHP
arr() function can't connect with database
class DB {
protected $db_server = 'localhost';
protected $db_username = 'root';
protected $db_password = 'root';
protected $db_name = 'dbname';
public function connect() {
$connect_db = new mysqli($this->db_server, $this->db_username, $this->db_password, $this->db_name);
if(mysqli_connect_errno()) {
printf("Connection failed!", mysqli_connect_error());
exit();
} else {
echo "connected";
}
return true;
}
function arr() {
$conn = $this->connect();
if($query = mysqli_query($conn, "SELECT * FROM users")) {
echo 'row is ' . mysqli_num_rows($query);
}
}
}
$db = new DB();
$db->arr();
result -> "connected row is " not count rows
In the connect() function, change
return true;
to
return $connect_db;
so that it returns the connection object. Then you can use it in your other functions.
I am confused where i made mistake in my php code below. Although, i looked numerous time on my code but couldn't find why i am getting this error 'cannot access empty property' .
class DBTest{
//declare variables
private $servername = "localhost";
private $username = "root";
private $password = "";
private $database = "avn_test";
private static $conn;
private $results;
//constructor
public function __construct(){
self::$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();}
} //close constructor
public function executeQuery($query='') {
if(!empty($query)){
$query = self::$conn->real_escape_string($query);
Error on this line:
$this->results = self::$conn->query($query) or die("Error in database
connection".self::$conn->$error);
if( $this->results->num_rows > 0 ) {
$rowqry = array();
while($row = $this->results->fetch_object()) {
$rowqry[]= $row; } //close of while
$rarray['returnvar'] = $rowqry;
return $rarray;
} else {
return false; } // close of else
}//close of top if
else
return false;
} //close of function
function __destruct(){
self::$conn->close();}
} //close of class
//create an object of class DBTest
$test = new DBTest();
$q= "select * from test";
$tmp = $test->executeQuery($q);
if($tmp){
foreach($tmp as $key => $value){
echo $value;}
}
else
echo 'tmp var is empty';
In this line:
$this->results = self::$conn->query($query) or die("Error in database connection".self::$conn->$error);
Replace self::$conn->$error with self::$conn->error.
The $ is required when accessing a static property, but not needed for instance properties.
No need of $ in $conn function
self::$conn replace with self::conn
^^^^^^
I'm trying to change my queries from mysql to PDO because I need to query at the same time two different databases on different servers.
I've done these classes so far
class Db extends PDO {
public $db;
public function __construct($dbhost = 'host1', $dbname = 'db1', $dbuser = 'user1', $dbpass = 'user2', $dbtype = 'mysql') {
PDO::__construct($dbtype . ':host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
}
function sql_query($sql) {
$result = PDO::query($sql);
return $result;
}
function sql_fetcharray($result) {
$rs = $result->fetch(PDO::FETCH_ASSOC);
return $rs;
}
function sql_numrows($result) {
$rs = $result->rowCount();
return $rs;
}
}
class Db2 extends Db {
public $db;
public function __construct($dbhost = 'host2', $dbname = 'db2', $dbuser = 'user2', $dbpass = 'pass2', $dbtype = 'mysql') {
PDO::__construct($dbtype . ':host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
}
function sql_query($sql) {
parent::sql_query($sql);
$result = PDO::query($sql);
return $result;
}
function sql_fetcharray($result) {
$rs = $result->fetch(PDO::FETCH_ASSOC);
return $rs;
}
function sql_numrows($result) {
$rs = $result->rowCount();
return $rs;
}
}
and then
$db = new Db2;
$sql = "query";
$result = $db->sql_query($sql);
but the query affects only the second database.
Anyone can help?
Thanks a lot
you had to run your query twice against two databases. don't expect the inheritance to do that for you
$db = new Db2();
$sql = "query";
$result = $db->sql_query($sql);
$db1 = new Db();
$sql = "query";
$result1 = $db1->sql_query($sql);
I don't think you needed another child class, you can easily switch database using :
USE DATABASENAME
So for example you can do:
$db = new Db;
$sql = "query";
$result = $db->sql_query($sql);
$db->sql_query('USE DB2');
$sql2 = "query2";
$result2 = $db->sql_query($sql2);
or perhaps create a function to select db:
function select_db($db) {
$result = PDO::query('USE $db');
return $result;
}
then use it:
$db = new Db;
$sql = "query";
$result = $db->sql_query($sql);
$db->select_db('DB2');
$sql2 = "query2";
$result2 = $db->sql_query($sql2);
I'm really new to implementing OOP using mysqli things, I have this Object(Class) named Database, my real problem is how would I call my select method in my index.php and how can I use it
Database Class.php is below:
Class Database{
private $host = null;
private $user = null;
private $pass = null;
private $db = null;
public $error = "Error Po Sir!";
public $con;
public function connect($host, $user, $pass, $db){
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->db = $db;
$this->con = mysqli_connect($this->host, $this->user, $this->pass);
if(mysqli_connect_errno()){
echo "Connection Failed %s\n!", mysqli_connect_error();
exit();
}
}
public function select($condition){
$query = "select os_user from users WHERE os_user = {$condition}";
$result = mysqli_query($this->con,$query);
return $result;
}
}
this is how did I implement it:
require 'templates/dbclass.php';
$db = new Database();
$db->connect("localhost", "root", "", "os_db");
$username = $_POST['username'];
if($result = $db->select($username)){
echo $username;
if($result->num_rows > 0){
while($row = $result->fetch_object()){
echo $row->os_id;
}
}
}
But it does not show any results. When I var_dump($result) I get bool(false).
I've enabled error reporting, but there is no errors displayed.
There are 3 issues with your select function
is is vulnerable to SQL injection
it does no error checking
it is useless
Here is how it have to be
public function query($sql, $bind)
{
$db = $this->con;
$stm = $db->prepare($sql) or trigger_error($db->error." [$sql]");
$types = str_repeat("s", count($values));
array_unshift($bind, $types);
call_user_func_array(array($stm, 'bind_param'), $bind);
$stm->execute() or trigger_error($db->error." [$sql]");
$stm->store_result();
return $stm->get_result();
}
used like this
$sql = "select os_user from users WHERE os_user = ?";
$res = $db->select($sql, $_POST['username']));
while($row = $result->fetch_object()){
echo $row->os_id;
}
I can't do a query.
This is my code, where I connect to database and try to query.
EDIT :
class DatabaseConnection {
private $host;
private $port;
private $dbname;
private $username;
private $password;
private $query;
function __construct($host, $port, $dbname, $username, $password) {
$this->host = $host;
$this->port = $port;
$this->dbname = $dbname;
$this->username = $username;
$this->password = $password;
try {
$conn = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
echo "PDO connection object created";
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
function setQuery($query) {
$this->query = $query;
$sth = $db->prepare($this->query);
$sth->execute();
$result = $sth->fetchAll();
var_dump($result);
}
}
$db = new DatabaseConnection('144.76.6.45','5432','eu','eu','eu123');
$db->setQuery('SELECT * FROM user');
This is my code, I don't have any errors, but still it doesn't work.....
Depending on the type of query you will want to fetch data after executing it. Take a look at fetch() and fetchAll() methods.
$sth = $db->prepare($this->query);
$sth->execute();
$result = $sth->fetchAll();
var_dump($result);
or use a loop and fetch row by row
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
var_dump($row);
}
after your edit:
Try to replace:
$conn = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
with
$this->db = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
and then call prepare method on it: $sth = $this->db->prepare($this->query); instead of $sth = $db->prepare($this->query);