How to use multiple database names as variables in mysql query in php -
i need write 2 mysql queries in php script, in both cases want data fetched 2 different databases on same server. database names stored in 2 different variables.
$link1 = mysql_connect($hostname_database,$username_database,$password_database); $database1 = "android1"; $database2= "android2"; $result1 = mysql_query("select * database1.tablename"); $result2 = mysql_query("select * database2.tablename");
what's correct way of achieving ?
this how you'll connect 2 databases. need send true fourth parameter in second connection, otherwise first connection used.
$db1 = mysql_connect($hostname, $username, $password); $db2 = mysql_connect($hostname, $username, $password, true); mysql_select_db('database1', $db1); mysql_select_db('database2', $db2);
then query first database :
mysql_query('select * tablename', $db1);
query second database :
mysql_query('select * tablename', $db2);
edit 1 : had used answer can't seem find answer.
edit 2 : found : how connect multiple mysql databases on single webpage?
edit 3 : preferred way :
if use php5 (and should, given php4 has been deprecated), should use pdo, since becoming new standard. 1 (very) important benefit of pdo, supports bound parameters, makes more secure code.
you connect through pdo, this:
try { $db = new pdo('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password'); } catch (pdoexception $ex) { echo 'connection failed: ' . $ex->getmessage(); }
(of course replace databasename, username , password above)
you can query database this:
$result = $db->query("select * tablename"); foreach ($result $row) { echo $row['foo'] . "\n"; }
or, if have variables:
$stmt = $db->prepare("select * tablename id = :id"); $stmt->execute(array(':id' => 42)); $row = $stmt->fetch();
if need multiple connections open @ once, can create multiple instances of pdo:
try { $db1 = new pdo('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password'); $db2 = new pdo('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password'); } catch (pdoexception $ex) { echo 'connection failed: ' . $ex->getmessage(); }
Comments
Post a Comment