PDA

View Full Version : insert data from a db toanother db


zodehala
04-12-2008, 09:26 PM
i wanna copy datas from forum to portal. iam using following codes but nthing. why? (even it doesnot give error )
<?php
$l1 = mysql_connect("localhost","root","123")or die();
$d1 = mysql_select_db("forum",$l1)or die();
$result = mysql_query("SELECT * FROM `user`");
while ($row = mysql_fetch_assoc($result)) {


$link = mysql_connect("localhost","root","123")or die();
$db = mysql_select_db("portal",$link)or die();

$insert = mysql_query(
"INSERT INTO aef_users (id,username)
VALUE(".$row["userid"].",".$row["username"]."");
}
?>

Andrew Johnson
04-12-2008, 09:28 PM
Nevermind the fact you're trying to go from 1 db to another, your insert statement isn't even using the correct syntax, strings aren't in quotes and theres no closing values parenthesis.

PappaJohn
04-12-2008, 09:41 PM
(even it doesnot give error )
And, you're doing no error checking or reporting, so why should it?

NancyJ
04-12-2008, 09:43 PM
It seems like everyone has their grumpy pants on today :S Your code isn't far off being right but there's a few mistakes and a few things that could be done better.

But as it appears they're both on the same database server, you could do it all in a single query. eg.

INSERT INTO portal.aef_users (id, username) (select userid, username from user)


Just incase you're they're on different database servers, this is how I would rewrite your code slightly


<?php
$l1 = mysql_connect("localhost","root","123")or die();
$d1 = mysql_select_db("forum",$l1)or die();
$result = mysql_query("SELECT * FROM `user`");

$link = mysql_connect("localhost","root","123")or die();
$db = mysql_select_db("portal",$link)or die();

while ($row = mysql_fetch_assoc($result)) {

$insert = mysql_query(
"INSERT INTO aef_users (id,username)
VALUES(".$row["userid"].",'".$row["username"]."')") or die(mysql_error());
}
?>


I've moved the mysql_select_db outside the loop because you *should* only need to do it once (though I have read php can be a little quirky working with multiple connections). I'm not clear on the internal workings, with regards to mysql resource identifiers so if this doesn't work, I would recommend looping through the dataset first and storing it into a php array then selecting the new db and doing a loop through your php array.

The other problems were the missing S off the end of VALUES, a missing closing parethesis on the query and the username should be quoted (assuming its a string of course).
I've also added or die(mysql_error()) after your query which will give you any mysql errors should they occur. mySQL errors are separate to php errors, your php code was perfectly valid as far as the compiler is concerned, it was within mysql that the error occured so you need to call the mysql_error() function to capture that.