I have two databases – lorem
and nts.lorem
– and need to operate with both of them
$user = 'root'; $pass = ''; $db1 = new PDO('mysql:host=localhost; dbname=nts.lorem', $user, $pass); $db2 = new PDO('mysql:host=localhost; dbname=lorem', $user, $pass);
everything works fine until db
is a variable in an ajax request – for example:
js
var db; if(something is true){db = 'db1';}; else{db = 'db2';} //... ajax post code
php
function something($db){ global $db1, $db2; // how to say the next line $sq = "select id from " . $db . ".tableName order by title asc"; // error - table db1.tableName doesn't exist }
any help?
Advertisement
Answer
Choose connection according to $db
value:
function something($db){ global $db1, $db2; $sq = "select id from tableName order by title asc"; if ($db === 'db1') { $db1->execute($sq); } else { $db2->execute($sq); } // rest of the code }