Addev
Addev

Reputation: 32243

Make an insert with the values returned by another query directly (PHP)

Im doing a PHP script for insert in the table A values recovered from the table B (A and B are in different databases).

 Table A Columns
 [index(autoincrement),timestamp(currenttimestamp),col1,col2,.....col15]

and I have the query for retrieve the values from B:

$query= "select count(*) as col1, XXX as col2.....ZZZ as col15 from B";

so having the

$row=$mysql_fetch_array($result) 

where

$result=mysql_query($query)

how can I make an

insert into A (col1,col2.....col15) values ($row['col1'],....$row['col15'];

easily without write all the code? Thanks

Upvotes: 0

Views: 71

Answers (2)

Wkter
Wkter

Reputation: 152

If you have to transfer the data across databases on different servers, you can use sprintf and implode to generate your query.

$query = sprintf('INSERT INTO table_name (%s) VALUES ("%s")', implode(', ', array_map('mysql_escape_string', array_keys($row))), implode('", "',array_map('mysql_escape_string', $row)));

Upvotes: 2

haltabush
haltabush

Reputation: 4528

Insert into db1.A (col1, col2, col3) SELECT col1, col2, col3 FROM db2.B

Upvotes: 4

Related Questions