Is it possible to connect to two different mysql databases? - php

I have 2 databases that I need to connect with but I don't know how to put the query in my code.
I have 2 pages of code. 1 for the form and the other to display the data after we have filled out the form. Will I need to put a new query on both pages or neither?
When I try to put a second connection on both pages, the whole page isn't working.
The connection I have made looks like this for both pages:
<?php
session_start();
include('conn.php');
include('connection2.php');
?>
For second database:
<?php
define('DB_HOST2','localhost');
define('DB_USER2','root');
define('DB_PASSWORD2','');
define('DB_NAME2','smile2');
$dbc = #mysql_connect(DB_HOST2,DB_USER2,DB_PASSWORD2) OR Die ('Could not connect to MySQL: '. mysql_error());
#mysql_select_db (DB_NAME2) OR Die ('Could not select database: '. mysql_error());
?>
For first database:
<?php
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_NAME','smile');
$dbc = #mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) OR Die ('Could not connect to MySQL: '. mysql_error());
#mysql_select_db (DB_NAME) OR Die ('Could not select database: '. mysql_error());
?>
How can I make #mysql_* change to:
<?php
//connect
mysql_connect("localhost", "user", "password");
//select first database
mysql_select_db("database_1");
//do query
mysql_query("SELECT * FROM `table` WHERE `field` = 1");
//select second database
mysql_select_db("database_2");
//do query on other database
mysql_query("SELECT * FROM `other_table` WHERE `field` = 2");
//you might wanna switch back to the first database
mysql_select_db("database_1");
?>

You can use the PHP function mysql_select_db to switch between databases. Like so:
<?php
//The preferred way:
//connect
mysqli_connect("localhost", "user", "password");
//select first database
mysqli_select_db("database_1");
//do query
mysqli_query("SELECT * FROM `table` WHERE `field` = 1");
//select second database
mysqli_select_db("database_2");
//do query on other database
mysqli_query("SELECT * FROM `other_table` WHERE `field` = 2");
//you might wanna switch back to the first database
mysqli_select_db("database_1");
//The old way
//connect
mysql_connect("localhost", "user", "password");
//select first database
mysql_select_db("database_1");
//do query
mysql_query("SELECT * FROM `table` WHERE `field` = 1");
//select second database
mysql_select_db("database_2");
//do query on other database
mysql_query("SELECT * FROM `other_table` WHERE `field` = 2");
//you might wanna switch back to the first database
mysql_select_db("database_1");
?>

<?php
class manageDB{
private $dbStatus = false;
private $mode = 'debug';
private $curCon = 'db1';
private $db = '';
private $con = '';
private $details = array(
'db1'=>array(
'server'=> '',
'user' => '',
'pass' => '',
'db' => ''
),
'db2'=>array(
'server'=> '',
'user' => '',
'pass' => '',
'db' => ''
)
);
//Init object
function __construct() {
$this->curCon = ($GLOBALS['isDebug']) ? 'db1' : 'db2';
}
public function defineDB($options, $type){
if(empty($type)){
$this->curCon = 'db1';
$this->details[$this->curCon]['server'] = $options['server'];
$this->details[$this->curCon]['user'] = $options['user'];
$this->details[$this->curCon]['pass'] = $options['pass'];
$this->details[$this->curCon]['db'] = $options['db'];
$this->con = null;
} else {
$this->curCon = $type;
}
$this->returnDB = FALSE;
if($this->dbStatus == TRUE) $this->open();
}
public function open(){
$this->con = mysql_connect($this->details[$this->curCon]['server'], $this->details[$this->curCon]['user'], $this->details[$this->curCon]['pass']);
if (!$this->con) { die('Could not connect: ' . mysql_error()); };
mysql_select_db($this->details[$this->curCon]['db'], $this->con);
$this->dbStatus = true;
}
public function close(){
mysql_close($this->con);
unset($this->connectStatus);
$this->dbStatus = false;
}
public function changeDB($db){
if($this->details[$this->curCon]['db'] != $db) mysql_select_db($db, $this->con);
$this->returnDB = TRUE;
return $this;
}
public function qry($query) {
$args = func_get_args();
if(count($args) > 1){
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
}
$result = mysql_query($query);
//Check if we need to return to default table
if(isset($this->returnDB)){
mysql_select_db($this->details[$this->curCon]['db'], $this->con);
$this->returnDB = FALSE;
}
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
}
public function checkStatus(){ echo $this->dbStatus; }
};
$db = new manageDB();
?>
Usage:
for normal operations use
$select = $db->query(...);
to switch database use
$select = $db->changeDB('db_name')->query(...);

easily done one step at a time, like here:
<?php
$link = mysql_connect("localhost", "mysql_user","mysql_password")
or die("Could not connect to MYSQL");
$selected_db = mysql_select_db('Database_Name', $link)
or die ('Sorry, could not connect to Database');
echo 'Connected successfully';
mysql_close($link);
?>
then the second one as:
<?php
$link = mysql_connect("localhost", "mysql_user","mysql_password")
or die("Could not connect to MYSQL");
$selected_db = mysql_select_db('Database_Name', $link)
or die ('Sorry, could not connect to Database');
echo 'Connected successfully';
mysql_close($link);
?>

Related

convert mySQL to mySQLi - using a class

The previous programmer had used a class called database that has the connection string and a bunch of functions. I now have to convert this to MySQLi and I am at a loss.
class database {
var $sql='';
var $result='';
function database( $host='localhost', $user, $pass, $db) {
// perform a number of fatality checks, then die gracefully
if (!function_exists( 'mysql_connect' )) {
//or die( 'FATAL ERROR: MySQL support not available. Please check your configuration.' );
exit();
}
bla..bla..bla - bunch of code goes here
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysql_query($sql);
return $result;
}
}
I tried
var $link=mysqli_connect('localhost', $user, $pass);
to use as
$result = mysqli_query($link,$sql);
but I can not use expression as a variable value and I don't know what else to do.
Thanks a bunch! :)
try to use this.
I think it solves your problem.
<?php
$link = mysqli_connect("localhost", $user, $pass, $databaseName);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
mysqli_set_charset($link, "utf8");
?>
just bring the $link in every query.
$link = mysqli_connect("localhost", $user, $pass, $db);
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysqli_query($link,$sql);
return $result;
}

PHP and SQL -- Select from database

I have a problem with this code. It has syntax error and I don't know what is it.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
if (!$conn) {
die('Could not connect: ' . mysql_error());
$sql = 'SELECT id FROM users WHERE email=\"donat12#icloud.com\"';
echo $sql;
?>
There are some issue with the code. First you forgot to close the if condition over here
if (!$conn) {
And then you forgot to execute the sql query
the complete code would be like
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id FROM users WHERE email=\"donat12#icloud.com\"';
if ($result = $conn->query($sql)) {
while ( $row = $result->fetch_assoc()) {
$data[] = $row;
}
echo "<pre>";
print_r($data);
echo "</pre>";
}
$conn->close();
?>
There are two errors
You are missing } closing bracket after die
Mysql query is wrong.
So the code should be
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id FROM users WHERE email="donat12#icloud.com"';
echo $sql;

PHP: Warning: mysql_fetch_array() expects parameter 1 to be resource

I got this error while adding this code. Would appreciate some help. It's for a CS jackpot site.
$sitename = "website.com"; // YOUR DOMAIN
$link = mysql_connect("localhost", "db_user", "db_pass"); // MYSQL , LOCALHOOST , USERNAME , PASSWORD
$db_selected = mysql_select_db('db_name', $link); // MYSQL DATABASE
mysql_query("SET NAMES utf8");
function fetchinfo($rowname,$tablename,$finder,$findervalue) {
if($finder == "1") $result = mysql_query("SELECT $rowname FROM $tablename");
else $result = mysql_query("SELECT $rowname FROM $tablename WHERE `$finder`='$findervalue'");
while($row = mysql_fetch_assoc($query))
return $row[$rowname];
}
Some tips:
Use mysqli better than mysql
Split the vars in the query, like "SELECT ".$rowname." FROM ".$tablename;
Hope this help...
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Select Query
$result = $mysqli->query("SELECT id, product_name FROM products");
while($row = $results->fetch_assoc()) {
echo $row["id"].' - '.$row["product_name"].'<br>';
}
$results->free();
$mysqli->close();

PHP MySQL connection error

guys!I got a littile trouble.
There is connection.inc.php in "includes" folder:
<?php
function dbConnect($usertype, $connectionType = 'mysqli') {
$host = 'localhost';
$db = 'testdb';
if ($usertype == 'read') {
$user = 'readuser';
$pwd = 'testpass';
} elseif ($usertype == 'write') {
$user = 'writeuser';
$pwd = 'testpass';
} else {
exit('Unrecognized connection type');
}
if ($connectionType == 'mysqli') {
return new mysqli($host, $user, $pwd, $db) or die('Cannot open database');
} else {
try {
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch(PDOException $e) {
echo 'Cannot connect to database';
exit;
} // end of try block
} // end of $connectionType if
} // end of function
I use Linux for this test,and the lastest xampp 1.7.4
But things become worse when I use the following code:(I already have created my DB, and two users 'readuser' and 'writeuser')
<?php
// I use mysqli extension to connect my DB
require_once(includes/connection.inc.php);
// connect to DB
$conn = dbConnect('read');
// I need to get some picture infomations from images table
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error());
// find out how many records were retrieved
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>
And when I load it in my browser:
Fatal error:Call to a member function query() on a non-object in /opt/lampp/htdocs/mysqli.php on line 9
So I guess $conn is not a object now,but It works when I write this code:
<?php
$host = 'localhost';
$user = 'readuser';
$pass = 'testpass';
$db = 'testdb';
$sql = 'SELECT * FROM images';
$conn = new mysqli($host, $user, $pass, $db);
$result = $conn->query($sql) or die(mysqli_error());
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>
And it outputs:We have 8 pictures in DB
That's really a strange thing,I can't figure it out...Thanks guys!
Try saving the new mysqli() result as a variable, then return that variable instead. That logic makes no sense, I know, but I've had problems like that before.
$a = new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
return $a;

where is the fatal error "Cannot access empty property" in the PHP class function?

What is wrong with this code?
<?php
class users {
var $user_id,
$f_name,
$l_name,
$db_host,
$db_user,
$db_name,
$db_table;
function users() {
$this->$db_host = 'localhost';
$this->$db_user = 'root';
$this->$db_name = 'input_oop';
$this->$db_table = 'users';
}
function userInput($f_name, $l_name) {
$dbc = mysql_connect($this->db_host , $this->db_user, "") or die ("Cannot connect to database : " .mysql_error());
mysql_select_db($this->db_name) or die (mysql_error());
$query = "insert into $this->db_table values (NULL, \"$f_name\", \"$l_name\")";
$result = mysql_query($query);
if(!$result) die (mysql_error());
$this->userID = mysql_insert_id();
mysql_close($dbc);
$this->first_name = $f_name;
$this->last_name = $l_name;
}
function userUpdate($new_f_name, $new_l_name) {
$dbc = mysql_connect($this->db_host, $this->db_user, "") or die (mysql_error());
mysql_select_db($this->db_name) or die (mysql_error());
$query = "UPDATE $this->db_table set = \"$new_f_name\" , \"$new_l_name\" WHERE user_id = \"$this->user_id\"";
$result = mysql_query($query);
$this->f_name = $new_f_name;
$this->l_name = $new_l_name;
$this->user_id = $user_id;
mysql_close($dbc);
}
function userDelete() {
$dbc = mysql_connect($this->db_host, $this->db_user, "") or die (mysql_error());
mysql_select_db($this->db_name) or die (mysql_error());
$query = "DELETE FROM $this->db_table WHERE $user_id = \"$this->user_id\"";
mysql_close($dbc);
}
}
?>
The error is:
Fatal error: Cannot access empty property in C:\xampp\htdocs\jordan_pagaduan\class.php on line 15.
To access a class-property from inside a method of a class, you must use $this->propertyName, and not $this->$propertyName.
Which means your user_input() method should be written like this :
function user_input() {
$this->db_host = 'localhost';
$this->db_user = 'root';
$this->db_name = 'input_oop';
$this->db_table = 'users';
}
(you might have to do the same modification to other places)
With what you have written, $this->db_user is never set ; and, later, when using this :
$dbc = mysql_connect($this->db_host , $this->db_user, "")
$this->db_user is null ; which means mysql_connect will use the default value -- which, in your case, appears to be ODBC, judging from the error message.
(same thing with the other properties -- but I took this one as an example, as the ODBC default-value was present in the error message you posted : it was the most obvious choice.)

Categories