Querying two databases with PDO - php

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);

Related

How to connect to database using mvc in php [duplicate]

This question already has an answer here:
PHP simple DB connection class for MVC
(1 answer)
Closed 1 year ago.
dbconnect.php
class dbconnect
{
public function connect()
{
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host, $user, $pass, $db);
return $connection;
}
}
dao.php
include 'dbconnect.php';
class dao extends dbconnect
{
private $conn;
function __construct()
{
$dbcon = new dbconnect();
$conn = $dbcon->connect();
}
function select($table, $where = '', $other = '')
{
if (!$where = '') {
$where = 'where' . $where;
}
$sele = mysqli_query($this->conn, "SELECT * FROM $table $where $other") or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
controller.php
include 'dao.php';
$d = new dao();
if (isset($_POST['btn_login'])) {
extract($_POST);
$username = $_POST['user_name'];
$pswd = $_POST['pswd'];
$sel = $d->select("users", "email_id = '" . $username . "'AND password='" . $pswd . "'") or die('error from here');
$result = mysqli_fetch_array($sel);
if ($result['email_id'] == $username && $result['password'] == $pswd) {
SESSION_START();
$_SESSION['user_name'] = $result['email_id'];
$_SESSION['message'] = 'Invalid Username Or Password';
header("location:index.php");
} else {
$_SESSION['error'] = 'Invalid Username Or Password';
}
}
I got an error
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /opt/lampp/htdocs/ankit_demo/dao.php on line 13
Warning: mysqli_error() expects parameter 1 to be mysqli, null given in /opt/lampp/htdocs/ankit_demo/dao.php on line 13
Please help me to solve this.
Try this out, there was issues with if condition as well as the where condition. and we can't echo a object or can't convert object to string.
dbconnect.php:
<?php
class dbconnect{
public function connect(){
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host,$user,$pass,$db);
return $connection;
}
}
dao.php:
<?php
include 'dbconnect.php';
class dao extends dbconnect {
private $conn;
public function __construct() {
$dbcon = new parent();
// this is not needed in your case
// you can use $this->conn = $this->connect(); without calling parent()
$this->conn = $dbcon->connect();
}
public function select( $table , $where='' , $other='' ){
if($where != '' ){ // condition was wrong
$where = 'where ' . $where; // Added space
}
$sql = "SELECT * FROM ".$table." " .$where. " " .$other;
$sele = mysqli_query($this->conn, $sql) or die(mysqli_error($this->conn));
// echo $sele; // don't use echo statement because - Object of class mysqli_result could not be converted to string
return $sele;
}
}
?>
controller.php:
<?php
include 'dao.php';
$d = new dao();
if(isset($_POST['btn_login'])){
extract($_POST);
$username = $_POST['user_name'];
$pswd = $_POST['pswd'];
$sel = $d->select("users" , "email_id = '" . $username . "' AND password='" . $pswd . "'" ) or die('error from here');
$result = mysqli_fetch_array($sel) ;
if($result['email_id'] == $username && $result['password'] == $pswd){
SESSION_START();
$_SESSION['user_name'] = $result['email_id'];
$_SESSION['message'] = 'Invalid Username Or Password';
header("location:index.php");
}
else{
$_SESSION['error'] = 'Invalid Username Or Password';
// header("Location:login.php");
}
}
?>
Change name of your constructor from __dao() to __construct().
Replace your line 6-th line of code by:
$this->conn = $dbcon->connect();
try this :
include 'dbconnect.php';
class dao extends dbconnect{
private $conn;
function __construct(){
$dbcon = new dbconnect();
$this->conn = $dbcon->connect();
}
function select( $table , $where='' , $other='' ){
if(!$where = '' ){
$where = 'where' . $where;
}
$sql = "SELECT * FROM ".$table." " .$where. " " .$other";
$sele = mysqli_query($this->conn, $sql) or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
Connection file:
class dbconnect{
public function connect(){
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host,$user,$pass,$db);
return $connection;
}
}
dao file:
include 'dbconnect.php';
class dao extends dbconnect {
private $conn;
public function __construct() {
$dbcon = new parent(); // this is not needed in your case
// you can use $this->conn = $this->connect(); without calling parent()
$this->conn = $dbcon->connect();
}
public function select( $table , $where='' , $other='' ){
if(!$where = '' ){
$where = 'where' . $where;
}
$sele = mysqli_query($this->conn,"SELECT * FROM $table $where $other") or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
But I think it would be better to use PDO or much better a ORM system like laravel eloquent.

Trying to display from mySQL using a class in php

I'm beginning php/MySql and have been asked to use a class to access my database. I can get the display to work when I have all my code in one file but when I try to call the class from another file, I get nothing.
This is the one that works:
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';
$myNewConnection = mysqli_connect($host,$username,$password,$dbname);
$query = "SELECT user_name FROM users" or die ("Error..." . mysqli_error($myNewConnection));
// execute the query
$result = $myNewConnection->query($query);
// display output
while($row = mysqli_fetch_array($result)) {
echo $row["user_name"] . "<br>";
}
?>
This is my code to call the class:
<?php
include("users.php");
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';
//initiate the class
$myDB = new MyDB('localhost', 'root', '', 'testdb');
//$myDB = new MyDB($host,$username,$password,$dbname);
?>
This is my class:
<?php
class MyDB {
public $query;
public $myConnection;
public function _construct($host,$username,$password,$dbname){
// establish the connection
$this->myConnection = mysqli_connect($host,$username,$password,$dbname);
}
public function list_users() {
// create query to list all users
$this->query = "SELECT user_name FROM users" or die ("Error..." . mysqli_error($this->$myNewConnection));
// execute the query
$result = $this->$myConnection->query($this->$query);
// display output
while($row = mysqli_fetch_array($result)) {
echo $row["user_name"] . "<br>";
}
}
}
?>
Any help appreciated
Change this line as below (remove the dollar sign from query and myConnection):
$result = $this->myConnection->query($this->query);
Plus you might need to call your list_users function using the code below (right after instantiating your class! Pass your defined variables to constructor instead of their actual values):
$myDB = new MyDB($host,$username,$password,$dbname);
$myDB->list_users();
Also constructors are written with two underscores like this:
public function __construct
function __construct with two "_". Delete all "$" after "->":
<?php
class MyDB {
public $query;
public $myConnection;
public function __construct($host,$username,$password,$dbname){
$this->myConnection = mysqli_connect($host,$username,$password,$dbname);
}
public function list_users() {
$this->query = "SELECT user_name FROM users";
if($result = $this->myConnection->query($this->query)) {
while($row = mysqli_fetch_array($result)) {
echo $row["user_name"] . "<br>";
}
}
}
}
And you have to run list_users():
<?php
include("users.php");
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';
$myDB = new MyDB($host, $username, $password, $dbname);
$myDB->list_users();
?>

Simple mySQLi select to an array

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);

Mysqli oop method call

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;
}

Get results from from MySQL using PDO

I'm trying to retrieve data from my table using PDO, only I can't seem to output anything to my browser, I just get a plain white page.
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$lastIndex = 2;
$sql = "SELECT * FROM directory WHERE id > :lastIndex AND user_active != '' LIMIT 20"
$sth = $conn->prepare($sql);
$sth->execute(array(':lastIndex' => $lastIndex));
$c = 1;
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo 'ALL STYLING ETC RESULTS HERE';
$c++;
}
$conn = null; // Disconnect
}
EXAMPLE.
This is your dbc class
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getAllData($qty) {
//prepared query to prevent SQL injections
$query = "select * from TABLE where qty = ?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $qty, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
$getList = $db->getAllData(25);
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}

Categories