我使用带有PHP和PHPMyAdmin的XAMPP作为接口,试图从一个数据库onlineportal查询信息,并在一个操作中插入另一个数据库androidchatterdatabase。由于下面的代码不允许从$dbOnlinePortal
查询信息,就好像我将查询语句从$dbOnlinePortal->query()
更改为$db->query()
,因此当从onlineportal.types和onlineportal.campaigns中选择时,它显示结果,但返回“0”。
我可以在PHP索引文件中启动另一个new MySQL
实例,从而同时连接到两个数据库吗?或者有没有比我现在做的更好的方法来访问一台服务器上的多个数据库?
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "androidchatterdatabase";
$dbName2 = "onlineportal";
$db = new MySQL($dbHost,$dbUsername,$dbPassword,$dbName);
$dbOnlinePortal = new MySQL($dbHost,$dbUsername,$dbPassword,$dbName2);
case "clickSpecial":
if ($userId = authenticateUser($db, $username, $password))
{
if (isset($_REQUEST['specialId']))
{
// Get data
$specialId = $_REQUEST['specialId'];
$timePeriod = $_REQUEST['timePeriod'];
$cityLocationId = $_REQUEST['cityLocationId'];
// Get the restaruant id, which will then serve to get the
// selected restaurant categories
$sqlRestaurantCategorization =
"SELECT distinct category_id
FROM onlineportal.types
WHERE user_id IN (SELECT DISTINCT user_id FROM onlineportal.campaigns WHERE id = '".$specialId."');";
// Get the categeories of the restraurant
if($getRestaurantCategorization = $dbOnlinePortal->query($sqlRestaurantCategorization))
{
// Insert those into the table
while($rowRestaurantCategorization = $dbOnlinePortal-> fetchObject($getRestaurantCategorization))
{
$sql22 = "INSERT INTO `users_click` (`usersId`, `restaurantCategoryId`, `timePeriod`, `cityLocationId`, `clickedDt`)
VALUES('".$userId."','".$rowRestaurantCategorization->restaurantCategoryId."','".$timePeriod."','".$cityLocationId."',NOW());";
error_log("$sql22", 3 , "error_log");
if ($db->query($sql22))
{
$out = SUCCESSFUL;
}
else
{
$out = FAILED;
}
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
}
else
{
$out = FAILED;
}
break;
最佳答案
使用insert stmt插入另一个数据库的语法如下:
USE `old_database`;
INSERT INTO `new_database`.`new_table`(`column1`,`column2`,`column3`)
SELECT `old_table`.`column2`, `old_table`.`column7`, `old_table`.`column5`
FROM `old_table`
编辑:
你试过这样做吗:
INSERT INTO `users_click` (`usersId`, `restaurantCategoryId`, `timePeriod`, `cityLocationId`, `clickedDt`)
VALUES ('".$userId."','(SELECT distinct category_id
FROM onlineportal.types
WHERE user_id IN (SELECT DISTINCT user_id FROM onlineportal.campaigns WHERE id = '".$specialId."'))','".$cityLocationId."',NOW());";