How to Connect Two Mysql database In PHP using Class - php

I am using Object oriented Php. For connecting Two database in same host I am using code like this
<?php
class ConOs{
var $dbhost1;
var $dbuser1;
var $dbpass1;
var $dbhost2;
var $dbuser2;
var $dbpass2;
function __construct() {
}
function connect(){
$this->dbhost1="localhost";
$this->dbuser1="user1";
$this->dbpass1="db1";
$this->dbhost2="localhost";
$this->dbuser2="user2";
$this->dbpass2="db2";
$conn1 = mysql_connect($this->dbhost1, $this->dbuser1, $this->dbpass1);
if(! $conn1 ){die('Could not connect: ' . mysql_error());}
mysql_select_db("db1",$conn1);
$conn2 = mysql_connect($this->dbhost2, $this->dbuser2, $this->dbpass2, True);
if(! $conn2 ){die('Could not connect: ' . mysql_error());}
mysql_select_db("db2", $conn2);
mysql_error();
}
}
?>
But $conn1 allways refused. Only $conn2 works. If I put $conn2 first, then only $conn1 works. How it possile to connect both database db1 & db2 ?

My dear stop to use mysql_* functions: use PDO :
class sujet{
private $id;
public function connect(){
try {
$bdd = new PDO('mysql:host=localhost;dbname=dev_bdd', 'root', '');
}catch(Exception $e){
die('Failed'. $e->getMessage());
}
return $bdd;
}
public function connect2(){
try {
$bdd = new PDO('mysql:host=localhost;dbname=teamd2', 'root', '');
}catch(Exception $e){
die('Failed'. $e->getMessage());
}
return $bdd;
}
public function __construct(){}
public function recherche($search){
$resultats = array();
$req = $this->connect2()->prepare('SELECT * FROM sujets WHERE libelle like :search ');
$req->execute(array(
'search' => '%'.$search.'%',
));
while($resultat = $req->fetch()){
array_push($resultats,$resultat);
}
print_r($resultats);
return $resultats;
}
private function queryMatiere(int $id){
$requete = $this->connect()->query("SELECT libelle FROM matieres where id=$id");
$data = $requete->fetch();
return $data['libelle'];
}
}

Related

Uncaught Error: Call to a member function prepare() (PDO, php)

I'm trying to get data from a table using a public function in PHP, but I get this error:
Uncaught Error: Call to a member function prepare() (PDO, php)
I'm searching for 2, 3 hours... But no result is similar or I did not understand.
<?php
class Config {
public static $SQL;
private function __construct() {
$host_name = "localhost";
$base_user = "root";
$base_pass = "";
$base_name = "home_page";
try {
self::$SQL = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);
self::$SQL->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
die("Something went wrong, database connection closed. Reason: ". $e->getMessage());
}
}
public static function GetData($table, $data, $id) {
$wc = Config::$SQL->prepare('SELECT `'.$data.'` FROM `'.$table.'` WHERE `ID` = ?');
$wc->execute(array($id));
$r_data = $wc->fetch();
return $r_data[$data];
}
}
?>
And I use this in my base file:
<h1><?php echo Config::GetData("page_details", "Moto", 1) ?></h1>
The error is from this line:
$wc = self::$SQL->prepare('SELECT `'.$data.'` FROM `'.$table.'` WHERE `ID` = ?');
Is there any particular reason why you want to use STATICeverywhere? The common approach is using public, dynamic methods and properties. I rewrote your sample with suggested naming convention in PHPs OOP, it works:
<?php
class Config
{
/** #var PDO $conn */
private $conn = null;
public function __construct()
{
$host_name = "localhost";
$base_user = "root";
$base_pass = "";
$base_name = "home_page";
try {
$this->conn = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully"; // <- this is unnnesesary
} catch (PDOException $e) {
die("Something went wrong, database connection closed. Reason: " . $e->getMessage());
}
}
public function findById($table, $data, $id)
{
$stmt = $this->conn->prepare('SELECT `' . $data . '` FROM `' . $table . '` WHERE `uid` = ?');
$stmt->execute(array($id));
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
// just for test
$cfg = new Config();
print_r($cfg->findById('foo', '*', 1));
or in your case
<?php echo $cfg->findById("page_details", "Moto", 1)['Moto'] ?>

DB class wont load

I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?

No records returned in PHP using OOP

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.

My first database connection

I've bought a domain-hosting from a local company. Their customer service is pretty horrible.
My code for connecting to the database seems ok but still its not working. Here my code:
function __construct(){
if(!#mysql_ping()){
$this->db_connect();
}
$sql = "SELECT value FROM settings WHERE field = 'auto_logout'";
$res = mysql_fetch_array($this->execute_single_query($sql));
$this->LOGIN_DURATION = $res['value'];
}
private function db_connect(){
// Mysql connect
$link = #mysql_connect('localhost', 'created_who_has_all_prev', 'pass_note_my_cpanel_and_mysql_has_same_pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully<br/>';
// Mysql select db select --->
$db_selected = mysql_select_db($this->DB, $link);
if (!$db_selected) {
die ('Can\'t use specified Database : ' . mysql_error());
}
//echo "<br/>Database Selected<br/>";
return $link;
}
And this is the snapshot:
Your main problem is that the link that you create isn't accessible. So, PHP tries to connect with defaults (apparently in your setup it means the user is root) and since it has no password, the connection fails which is the cause of most of your warning messages.
The last warning is a consequence of the others.
To fix this problem - as you haven't provided details of the actual parts that are executing the query - here is how to re-write your code so it works:
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "(".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql = "SELECT `value` FROM `settings` WHERE `field` = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s","auto_logout");
if (!$stmt->execute()) {
echo "(".$stmt->errno.") ".$stmt->error;
}
$res = $stmt->get_result();
$row = $res->fetch_assoc();
LOGIN_DURATION = $row['field'];
This is really sloppy code. I would use PDO as it is secure. Below is a class you can use but study how it works and why it works.
class Core {
public $dbh; // handle of the db connection
private static $instance;
private function __construct() {
$options = array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->dbh = new PDO("mysql:host=localhost;dbname=dealership", "root", "",$options);
}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __clone() {}
private function __wakeup() {}
}
In your code call it like below:
require "/classes/pdo.class.php";
$db = Core::getInstance();
$stmt = "SELECT `lastname` FROM `employees` where id = 2";
$pep = $db->dbh->prepare($stmt);
$pep->execute();
foreach($pep->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo $row['lastname']. "\n";
}
Make sure you look into PDO, prepared statments, and singleton pattern to understand why it works.

Passing db connection between functions

I'm fairly new at PHP and so maybe this is a simple question. This is a class I use to update a database. The problem is that it keeps giving me an error at the line marked * because it can't find $con, which is clearly in the function openconn(). It seems I can't pass the connection to another function. Am I doing something wrong?Thanks
class retreats {
public $retreat_name = '';
function openconn() {
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("PHPTest", $con);
}
function closeconn(){
mysql_close($con);
}
function add_retreat(){
openconn();
$sql="INSERT INTO tbl_retreats (retreat_name) VALUES ('".$this->retreat_name."')";
if (!mysql_query($sql,$con)) *******
{
die('Error: ' . mysql_error());
}
echo "Record Successfully Added";
closeconn();
}
}
$con is a local variable for the function openconn. Try to change your code in this way:
class retreats {
public $retreat_name = '';
private $con;
function openconn() {
$this->con = mysql_connect("localhost","root","root");
if (!$this->con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("PHPTest", $this->con);
}
function closeconn(){
mysql_close($this->con);
}
function add_retreat(){
openconn();
$sql="INSERT INTO tbl_retreats (retreat_name) VALUES ('".$this->retreat_name."')";
if (!mysql_query($sql,$this->con))
{
die('Error: ' . mysql_error());
}
echo "Record Successfully Added";
closeconn();
}
}
A Simple PDO port of your code...
<?php
class pdoDB{
//PDO Connect
function connect($host,$db,$user,$pass){
$this->dbh = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass);
}
function query($query){
$this->retreat_name = $query;
$this->prepare();
}
function prepare(){
/* Execute a prepared statement by binding PHP variables */
$this->sth = $this->dbh->prepare('INSERT INTO tbl_retreats (retreat_name) VALUES (:value)');
$this->sth->bindParam(':value', $this->retreat_name);
$this->execute();
}
function execute(){
$this->sth->execute();
}
function result(){
if ($this->sth->rowCount() > 0) {
return 'Record Successfully Added';
}else{
return 'Record Not Inserted';
}
}
function close(){
$this->sth = null;
}
}
$db = new pdoDB();
$db->connect('localhost','PHPTest','root','pass');
$db->query('Barcelona'); //or $db->query($_POST['retreat_name']);
echo $db->result();
$db->close();
?>
You need to first declare the $con in the class. Just put it after the public $retreat_name = '';
put
public $retreat_name = '';
private $con;
after that, you can use it in other functions using the $this keyword.
mysql_close($this->con);
it turns out you need to do this
$this->openconn();
instead of just
openconn();

Categories