connect for 2 Databases - php

There is a problem with a connection to DB.
Used class for DB
class DB
{
public static $connect = false;
private $database_host = 'localhost';
private $database_user = '';
private $database_pass = '';
private $database_db = '';
private $database_type = 'mysql';
function __construct($database_host, $database_db, $database_user, $database_pass)
{
$this->database_host = $database_host;
$this->database_db = $database_db;
$this->database_user = $database_user;
$this->database_pass = $database_pass;
if (self::$connect === false) {
$this->connect();
}
}
private function connect()
{
$dsn = $this->database_type . ":dbname=" . $this->database_db . ";host=" . $this->database_host;
try {
self::$connect = new PDO($dsn, $this->database_user, $this->database_pass, array(PDO::ATTR_PERSISTENT => false, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
self::$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//var_dump(self::$connect);
if(!self::$connect) {
die("Cannot connect to DB");
}
} catch (PDOException $e) {
die("Cannot connect to DB");
}
}
}
This connect, for 2 DB
$connect = new DB(_DB_HOST_, _DB_NAME_, _DB_USER_, _DB_PASS_);
$connectSlave = new DB(_DB_HOST_, _DB_NAME_, _DB_USER_, _DB_PASS_);
First connect - good, second - Fatal error: Access to undeclared static property: DB::$connectSlave
Please help me.

$connect should be an instance variable instead of static (otherwise it's shared between DB instances):
public $connect = false;
Then use $this->connect instead of self::$connect. Here's your class:
class DB
{
public $connect = false;
private $database_host = 'localhost';
private $database_user = '';
private $database_pass = '';
private $database_db = '';
private $database_type = 'mysql';
function __construct($database_host, $database_db, $database_user, $database_pass)
{
$this->database_host = $database_host;
$this->database_db = $database_db;
$this->database_user = $database_user;
$this->database_pass = $database_pass;
if ($this->connect === false) {
$this->connect();
}
}
private function connect()
{
$dsn = $this->database_type . ":dbname=" . $this->database_db . ";host=" . $this->database_host;
try {
$this->connect = new PDO($dsn, $this->database_user, $this->database_pass, array(PDO::ATTR_PERSISTENT => false, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
$this->connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//var_dump(self::$connect);
if(!$this->connect) {
die("Cannot connect to DB");
}
} catch (PDOException $e) {
die("Cannot connect to DB");
}
}
}

Related

I want to display table rows in same class and difference function in PHP

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.

how can i transform mysql to PDO connection?

How can I transform the mysql code bellow into pdo connection ? because i have some networking issues.
$gaSql['user'] = "root";
$gaSql['password'] = "";
$gaSql['db'] = "test";
$gaSql['server'] = "localhost";
// DB connection
function dbinit(&$gaSql) {
// if error rezults 500
function fatal_error($sErrorMessage = '') {
header($_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error');
die($sErrorMessage);
}
// connecting to mysql
if ( !$gaSql['link'] = #mysql_connect($gaSql['server'], $gaSql['user'], $gaSql['password']) ) {
fatal_error('Could not open connection to server');
}
// select the DB
if ( !mysql_select_db($gaSql['db'], $gaSql['link']) ) {
fatal_error('Could not select database');
}
}
Proper PDO db connection
<?php
$host = '127.0.0.1';
$db = 'your db';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $user, $pass, $options);
?>
Reference : https://phpdelusions.net/pdo
I use this in all my pdo connections it works perfectly
You could try something like this:
try {
$pdo = new PDO('mysql:host=' . $gaSql['server'] . ';dbname=' . $gaSql['db'], $gaSql['user'], $gaSql['password']);
} catch (PDOException $ex) {
if ($ex->getCode() == 1049) {
throw new Exception('Unknown Database: ' . $gaSql['db']);
} elseif ($ex->getCode() == 1045) {
throw new Exception('Wrong credentials for user: ' . $gaSql['user']);
}
}
Hope, this helps ;-)

Object couldn't be converted to string

I'm getting this error message when trying to make a PDO connection:
Object of class dbConnection could not be converted to string in (line)
This is my code:
class dbConnection
{
protected $db_conn;
public $db_name = "todo";
public $db_user = "root";
public $db_pass = "";
public $db_host = "localhost";
function connect()
{
try {
$this->db_conn = new PDO("mysql:host=$this->$db_host;$this->db_name", $this->db_user, $this->db_pass);
return $this->db_conn;
}
catch (PDOException $e) {
return $e->getMessage();
}
}
}
The error is on the PDO line. Just in case, I insert the code where I access to the connect() method:
class ManageUsers
{
public $link;
function __construct()
{
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $link;
}
function registerUsers($username, $password, $ip, $time, $date)
{
$query = $this->link->prepare("INSERT INTO users (Username, Password, ip, time1, date1) VALUES (?,?,?,?,?)");
$values = array($username, $password, $ip, $time, $date);
$query->execute($values);
$counts = $query->rowCount();
return $counts;
}
}
$users = new ManageUsers();
echo $users->registerUsers('bob', 'bob', '127.0.0.1', '16:55', '01/01/2015');
Change your connection setting to the following:
class dbConnection
{
protected $db_conn;
public $db_name = "todo";
public $db_user = "root";
public $db_pass = "";
public $db_host = "localhost";
function connect()
{
try {
$this->db_conn = new PDO("mysql:host={$this->db_host};{$this->db_name}", $this->db_user, $this->db_pass); //note that $this->$db_host was wrong
return $this->db_conn;
}
catch (PDOException $e) {
//handle exception here or throw $e and let PHP handle it
}
}
}
In addition, returning values in a constructor has no side-effects (and should be prosecuted by law).
Please follow below code , its tested on my server and running fine .
class Config
{
var $host = '';
var $user = '';
var $password = '';
var $database = '';
function Config()
{
$this->host = "localhost";
$this->user = "root";
$this->password = "";
$this->database = "test";
}
}
function Database()
{
$config = new Config();
$this->host = $config->host;
$this->user = $config->user;
$this->password = $config->password;
$this->database = $config->database;
}
function open()
{
//Connect to the MySQL server
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->database, $this->user,$this->password);
if (!$this->conn)
{
header("Location: error.html");
exit;
}
return true;
}

php oop database query

I am self learning php and trying oop, I am struggling with following problem, Would anyone could help me how can I use following database connection in to another class function. In php.net it is defined as $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db'); but when I use this within a class it dose not work. Thanks
class dbconnect{
private $host;
private $user;
private $pass;
private $dabase;
function doConnect()
{
$this->host = 'localhost';
$this->user = 'root';
$this->pass = 'abc#123';
$this->dabase = 'database_5';
$db = new mysqli($this->host, $this->user, $this->pass, $this->dabase);
if (mysqli_connect_errno())
{
echo "<br /><hr />";
echo "<p style='align:center;'>Error : could not connect to database.. </p>";
echo "<hr />";
exit;
}
}
$mysql = new dbconnect();
function doQuery($mysql){
$queryUser = $mysql->query("SELECT * FROM b_admin_user WHERE username_d = 'admin'");
echo $queryUser_row = $queryUser->num_rows;
}
doQuery($mysql);
Try this
<?php
class MySQL {
//objekto kintamieji
private $host;
private $username;
private $password;
private $database;
private $conn; // connection
public function __construct($set_host, $set_username, $set_password){
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
// jungiuosi prie db
$this->conn = mysql_connect($this->host, $this->username, $this->password)
or die("Couldn't connect");
}
public function database($set_database)
{
$this->database=$set_database;
//pasirenku lentele
mysql_select_db($this->database, $this->conn) or die("cannot select Database");
}
}
// jungiames
$connect = new MySQL('localhost','root','');
$connect->database('job');
?>

PHP mySQL connection problems

Ok, I am completely baffled.
I am setting up an OO site. I have a class that defines all my database params, as follows:
$db->host= "localhost";
$db->name= "mydatabase";
$db->user= "user";
$db->pw = "password";
The class is being instantiated correctly and the values show up in pages that appear after this class has been loaded.
BUT, when I try to connect to this database from a different class, it does not connect. Here's how I am connecting:
$dbconn = mysql_connect($db->host, $db->user, $db->pw);
mysql_select_db($db->name, $dbconn);
Everything works fine if I take out the user, pw and name variables and hard code in the correct values, but if any of them is referenced using the db construct, no connection happens. Again, the db construct appears just fine on other pages and I am seeing the variable values being presented correctly. The $db->host variable, however, always works.
Here's is how I am constructing the db class:
class database {
var $host;
var $name;
var $user;
var $pw;
function __construct($host = "localhost", $name = "mydatabase", $user = "user", $pw = "password"){
$this->host = $host;
$this->name = $name;
$this->user = $user;
$this->pw = $pw;
}
}
and then I of course do
$db = new database();
Thanks in advance for any help!
Don't use PHP4
Why don't you just use PDO
What's the point of storing password or username as a object property?
Probably the problem is a $db variable scope
How to fix all of that?
class MyClass {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
public function doSth() {
$this->db->query('..');
}
}
$db = new PDO('mysql:dbname=mydatabase;host=localhost', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$obj = new MyClass($db);
$obj->doSth();
I think u are not passing parameters when creating object for initializing the database class constructor.
try using
$db=new database("localhost","dbname","user","password");
and then create the class as
class database {
var $host;
var $name;
var $user;
var $pw;
function __construct($host , $name , $user , $pw ){
$this->host = $host;
$this->name = $name;
$this->user = $user;
$this->pw = $pw;
}
Also include this class as file if written separately
and for connection u can now write
$conn=mysql_connect($db->host,$db->user,$db->pw);
mysql_select_db($db->name,$conn);
Hope this helped :)
<?php
/*
link.php
Created By Nicholas English
*/
$link = null;
$connection = null;
$servername = "";
$username = "";
$dbname = "";
$pass = "";
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
$type = 3;
if ($type === 1) {
$mysqli = true;
$pdo = false;
$obj = true;
$pr = false;
} else {
if ($type === 2) {
$mysqli = true;
$pdo = false;
$obj = false;
$pr = true;
} else {
if ($type === 3) {
$mysqli = false;
$pdo = true;
$obj = false;
$pr = false;
} else {
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
}
}
}
if ($mysqli === true && $obj === true) {
$link = new mysqli($servername, $username, $pass, $dbname);
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$connection = true;
} else {
if ($mysqli === true && $pr === true) {
$link = mysqli_connect($servername, $username, $pass, $dbname);
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
$connection = true;
} else {
if ($pdo === true && $mysqli === false) {
try {
$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $pass);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection = true;
}
catch(PDOException $e)
{
$connection = null;
echo "Connection failed: " . $e->getMessage();
}
} else {
$link = null;
$connection = null;
}
}
}
if ($connection == null && $link == null) {
$error = 1;
}
?>
Use mysqli or pdo for a more secure connection

Categories