See the code below, there are two databases connections.
First it get the data from first connection and then insert into second database connection but it will not insert - I can an error saying Unknown column 'fullname' in 'field list'
When I tried SQL query manually in phpMyAdmin and it work fine...
$db_new = mysql_connect('localhost', 'root', 'password');
if (!mysql_select_db("menu_new", $db_new)) {
die("Cant connect menu_new DATABASE");
}
开发者_开发百科$db_old = mysql_connect('localhost', 'root', 'password');
if (!mysql_select_db("old_menu", $db_old)) {
die("Cant connect old_menu DATABASE");
}
$SQL_old = "SELECT * FROM old_table";
$q = mysql_query($SQL_old, $db_old);
while ($row = mysql_fetch_assoc($q)) {
$name = $row['name'];
$SQL = "INSERT INTO tbl_name (fullname) values ('$name')";
//Problem Here - It wont insert into second database
mysql_query($SQL, $db_new) or die(mysql_error($db_new));
}
Nothing is strange in this behavior. Just add the $link parameter on your mysql_connect calls, and set it to true. By default it is False and it means that reusing this function with the same parameters, which is what you're doing as the db name is not on your mysql-connect, will reuse existing connexion with same parameters. So you have two variables but only one connexion.
It means you're simply moving the db used in this connexion. Prefixing with the db name fixed the problem as MySQL allow inter-base manipulations from the same connexion if it's on the same db server.
Thanks @Konerak for suggestion and that does work!
To Insert/Select data from Database connection, you will have to include database name before the table name.
For Example
From:
mysql_query("INSERT into tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new));
To:
mysql_query("INSERT into menu_new.tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new));
That is really odd though.
精彩评论