How can i connect to two databases at the same time if both databases are on the same host and i have full privileges on both databases. So i have DB-1 and DB-2. And in this case i would like to have the following script working with the two databases. Im currently using require("db.php"); to connect to one database but i would like to connect to both databases.
require("DB-1.php");
$tbl_name="System_Info";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT COUNT(a.student_id)
FROM DB-1.TableA a
INNER JOIN DB-2.TableB b ON a.student_id = b.student_id
WHERE a.account_status = 'AVTIVE'
AND a.semesteer = '6'
AND b.assesor_status = 'PENDING'";
$q = mysql_query($sql) or die("Query failed: ".mysql_error());
while ($row = mysql_fetch_array($q))
{
echo '' . $row[0];
}
and this is what its using on DB-1 to connect
db-1.php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="DB-1"; // Database name
With MySQLi you can store the different DB connections in different variables.
<?php
$mysqlOne = new mysqli("localhost", "user", "password", "database_1");
echo $mysqlOne->host_info . "\n";
$mysqlTwo= new mysqli("127.0.0.1", "user", "password", "database_2", 3306);
$result = $mysqlTwo->query("SELECT Name FROM City LIMIT 10");
Remember, you could also utilize one database connection and just change the database you're using in the SQL, such as SELECT * FROM database3.city
See: http://www.php.net/manual/en/mysqli.quickstart.connections.php
Use mysqli (or PDO) extension for this. Mysql extension (without i) is bit outdated, and its usage is disencouraged. With mysqli you can easily make and handle several (different) connections to DB.
See: http://www.php.net/manual/en/mysqli.quickstart.connections.php
I will also recommend you to use mysqli or PDO for connecting with mysql as mysql extension is deprecated in PHP5.5.
Additionally If you dont want to move and want to run your current code, then here is the solution :
1). First remove mysql_select_db("$db_name")or die("cannot select DB");
2). and Use table names with their respective database names e.g. DBName.TableName
It should work!
Related
This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 3 years ago.
I am a beginner and also a diploma student...
please help me solve this error... I tried many online solution but it cant help ... I'm new to php and mysql...
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="slr"; // Database name
$tbl_name="software"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$soft_name=$_POST['soft_name'];
$installed_date=$_POST['installed_date'];
$expiry_date=$_POST['expiry_date'];
$product_key=$_POST['product_key'];
// Insert data into mysql
$sql="INSERT INTO $software(soft_name, installed_date, expiry_date, product_key)VALUES('$soft_name', '$installed_date', '$expiry_date', '$product_key')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='CreateData.php'>Back to main page</a>";
} else {
echo "ERROR";
}
// close connection
mysql_close();
?>
You should use mysqli_connect instead of mysql_connect which is deprecated since PHP 5.5.0 :
$link = mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($link, $db_name)or die("cannot select DB");
Try This:
Old way:
<?php
$link = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('testdb', $link);
mysql_set_charset('UTF-8', $link);
?>
New way: all you gotta do is create a new PDO object. PDO's constructor takes at most 4 parameters, DSN, username, password, and an array of driver options.
A DSN is basically a string of options that tell PDO which driver to use, and the connection details... You can look up all the options here PDO MYSQL DSN
<?php
$db=new PDO('mysql:host=localhost;dbname=slr;charset=utf8mb4', 'root', '') or die("Could connect to Database");
?>
According to Here.
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 7 years ago.
Hi i need some help in coding php to connect database
my source code is
$host="127.0.0.1"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="forum_question"; // Table name
// Connect to server and select databse.
`mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name ORDER BY id DESC";`
But it display error
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\123\tryforum\main_forum.php on line 11
cannot select DB
How to solve it
You need to pass connection variable to mysqli_select_db.
See this link
$host="127.0.0.1"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="forum_question"; // Table name
// Connect to server and select databse.
$con = mysqli_connect("$host", "$username", "$password") or die("cannot connect");
mysqli_select_db($con, "$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name ORDER BY id DESC";`
mysqli_select_db()
needs two parameter first your database connection and second your
database name
$conn=mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($conn,"$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name ORDER BY id DESC";
$result=mysqli_query($conn,$sql);
I'm having a little problem with php, basically I want to get a random row from my mysql database, I am really new to php and mysql so please be kind and explain me what's going on. I've already granted all permissions on mysql, now I just have to figure out what's going on, i tried to put some echoes to debug but it seems like anything happens, there's just a blank page with nothing on it, this drives me crazy so I'd like to resolve it. Here's the code
<?php
echo "test";
$host="127.0.0.1"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="mine"; // Database name
$tbl_name="accounts"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Select a random account
$min=1;
$row=mysql_fetch_assoc(mysql_query("SHOW TABLE STATUS LIKE 'mine.accounts';"));
$max=$row["Auto_increment"];
$random_id=rand($min,$max);
$row=mysql_fetch_assoc(mysql_query("SELECT * FROM `mine`.`accounts` WHERE id='$random_id'");
echo $row["username"]. ":" . $row["password"]
?>
// --- UPDATE ---
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$host="127.0.0.1"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="mine"; // Database name
$tbl_name="accounts"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Select a random account
$row = mysql_query("SELECT username AND password FROM accounts order by RAND() LIMIT 1");
WHILE ($data = mysql_fetch_array($row))
ENDWHILE;
echo $row['username'] . " " . $row['password'];
?>
On this line, you forgot the closing parentheses.
$row=mysql_fetch_assoc(mysql_query("SELECT * FROM `mine`.`accounts` WHERE id='$random_id'");
Hence the single closing parentheses while you open two.
$row=mysql_fetch_assoc(mysql_query("SELECT * FROM `mine`.`accounts` WHERE id='$random_id'"));
And you'll have to use a while loop to make $row output anything, since fetch_assoc returns an associative array:
while($row = mysql_fetch_assoc(<...>){
$max = $row['Auto_increment'];
}
Also you might wanna look into Prepared Statements or PDO as mysql_* Functions are officially deprecated.
I've got two different sites. What I'd like to do is to automatically run a script that sends some of the data inserted into the database in site 1 when a user registers and updates a table in the database for site 2 so that an account is automatically created in site 2 using the same details.
I'm at the stage of trying to create a query that will update the database. I'm the self-made type so don't know that well what I'm doing. Got this query from somewhere but can't make it work. Can anyone tell what's wrong with it? It's not executing the query.
Thanks!
Eugenie
<?php
$host = "localhost"; // Host name
$username = "----"; // Mysql username
$password = "----"; // Mysql password
$db_name1 = "------"; // Database name
$db_name2 = "-----"; // Database name
$tbl_name1 = "-----"; // Table name
$tbl_name2 = "---"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name1")or die("cannot select DB");
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name2")or die("cannot select DB");
$query = "USE $db_name2
UPDATE $db_name2.dbo.$tbl_name2
SET email=d2.email FROM $db_name1.dbo.$tbl_name1 d2
WHERE d2.uid = $tbl_name1.uid";
$result = mysql_query($query) or die ("could't execute query.");
?>
<?php
$host = "localhost"; // Host name
$username = "----"; // Mysql username
$password = "----"; // Mysql password
$db_name1 = "------"; // Database name
$db_name2 = "-----"; // Database name
$tbl_name1 = "-----"; // Table name
$tbl_name2 = "---"; // Table name
$conn = mysql_connect($host, $username, $password);
mysql_select_db($db_name1, $conn) or die("cannot select DB");
mysql_select_db($db_name2, $conn) or die("cannot select DB");;
$query1 = "SELECT * FROM `" . $db_name1.$tb1_name1 . "` ";
$query2 = "SELECT * FROM `" . $db_name2.$tb1_name2 . "` ";
You can fetch data of above query from both database as below
$result1 = mysql_query($query1);
while($row = mysql_fetch_assoc($result1)) {
$data1[] = $row;
}
$result2 = mysql_query($query2);
while($row = mysql_fetch_assoc($result2)) {
$data2[] = $row;
}
print_r($data1);
print_r($data2);
?>
Suggestion: Try shifting to mysqli or PDO since mysql is depreciated now.
Recall the documentation for mysql_connect:
Returns a MySQL link identifier on success or FALSE on failure.
... and the documentation for the second parameter for mysql_query:
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
... should solve your problem. Example:
$link1 = mysql_connect( ... ); // For db 1.
$link2 = mysql_connect( ... ); // For db 2.
$result1 = mysql_query( "some query for db 1", $link1 );
$result2 = mysql_query( "some query for db 2", $link2 );
Well,
first of all, you're not connecting to two different databases, but using two different schemas in the same database. So only a mysql_connect should be used.
Also, if you're using full qualified names to access your tables you don't need to call mysql_select_db, nor the 'use db_name' mysql command.
Your query string is wrong. After USE $db_name2 you should have a semi-colon, and the update sentence is not correct.
Code could be somthing like that:
mysql_connect(...)
$query = "update $db2.$table2, $db1.$table1
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning when using mysql_fetch_assoc in PHP
i am having a problem with the following codes, i am new in encountering this error
here is the code
session_start();
$uname=$_SESSION['login'];
$host="localhost";
$username="root";
$password="";
$db_name="sampledb";
$tbl_name="tblsched";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT * FROM tblteacher WHERE teacherName=$uname";
$result=mysql_query($sql);
$row = mysql_fetch_assoc($result);
$teacherid = $row['teacherID'];
it gives me a "mysql_fetch_assoc() expects parameter 1 to be resource, boolean" error, how do i deal with this error?? i have used this code already a few times in other files and it worked perfectly except now, i checked the names of the rows and it was correct
i already tried using other commands such as mysql_fetch_array, mysql_result, mysql_fetch_row and it gives the same error
You seem to be using a variable that is a string, you need to encapsulate it in quotes:
SELECT * FROM tblteacher WHERE teacherName='$uname'
On that note, I see that it is coming from a Session variable, I take it that it is already cleansed to make sure there are no possible injection attacks within it - yes?
Try
$sql = "SELECT * FROM tblteacher WHERE teacherName='$uname'";
The problem is in this line
$sql = "SELECT * FROM tblteacher WHERE teacherName=$uname";
change to
$sql = "SELECT * FROM tblteacher WHERE teacherName='$uname'";
the uname is string and it should be quoted using single or double quotes.
Try This // user index no
session_start();
$uname=$_SESSION['login'];
$host="localhost";
$username="root";
$password="";
$db_name="sampledb";
$tbl_name="tblsched";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT * FROM tblteacher WHERE teacherName=$uname";
$result=mysql_query($sql);
$row = mysql_fetch_assoc($result);
**$teacherid = $row[0];**