我的本地主机上有多个使用相同用户名和密码的数据库。由于信息存储在不同的数据库中,我需要跨数据库工作,同时打开两个数据库。我将数据插入到一个 DB 中,并希望删除另一个 DB 中的表以及数据。
这是我目前正在尝试的连接方式:
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = "@"; // Mysql password
$db_name = "etrack"; // Database 1
$db_name2 = "gs"; // Database 2
// Create connection
$conn = new mysqli($host, $username, $password, $db_name);
$conn2 = new mysqli($host, $username, $password, $db_name2);
// Check connection
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
然后我运行了一些SQL字符串,其中一个例子是:
$sql = "INSERT INTO unit_hx SET
imei = '".$imei."',
model = '".$model."',
supp = '".$supp."',
status = 'Scrapped',
installer = '".$installer."',
unit_nr = '".$unit_nr."',
cost = '".$cost."',
systime = '".$time."',
msisdn = '".$msisdn."',
sysdate = '".$date."',
notes = '".$notes."',
staff = '".$agent."'";
我想根据在数据库eTrack中检索到的IMEI信息在数据库GS中删除表:
DROP TABLE 'gs_object_data_'".$imei."'
//imei information is set on the page from a previous form using $_POST
用DB1中的信息是否可能查询DB2和删除DB2的表?
更新工作代码:要在两个不同的数据库中插入或更新信息,以下代码非常有用:
"INSERT INTO etrack.simcard_hx SET" //etrack is the database name simcard_hx is the table name
Changing database to other database I used
"INSERT INTO gs.simcard_hx SET" // gs being the second database
Your root
user should have access to both databases, so you shouldn't need the second connection. If it doesn't, create a user that does, it will simplify your life. Then, in queries you can just prefix your table names with the database name: e.g.
SELECT *
FROM etrack.table1 t1
JOIN gs.table2 t2 ON t2.etrack_id = t1.id