Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert return value of one SQL command into another table using PHP

Tags:

php

mysql

I have two servers hosting two different sites with two separate databases. However, some of the data needs to be shared - so there's a CRON that runs to copy that data from the first site to the second site. These two sites used to run on the same server, but now we have separated them so I'm attempting to amend the PHP to be able to handle this.

Here is the code where I'm encountering the problem:

$sql = "SELECT * FROM site1.events";
$events = mysql_query($sql, $site1db);  

$sql = "INSERT INTO site2.events SELECT * FROM $events";
$doIt = mysql_query($sql, $site2db);

Now I know that the SELECT * FROM site1.events is successful, but it cannot insert into the second site and I'm not seeing any sort of error. I've never written PHP before (this is a legacy task) so if it's something that's been covered before - do point me in the right direction.

Please note that site2.events is truncated before these commands so no compare is necessary.

like image 732
ediblecode Avatar asked May 11 '15 09:05

ediblecode


People also ask

How do I pass values from one table to another in SQL?

The SQL INSERT INTO SELECT Statement The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

How can I use one SQL query result in another?

Use the results of a query as a field in another query. You can use a subquery as a field alias. Use a subquery as a field alias when you want to use the subquery results as a field in your main query. Note: A subquery that you use as a field alias cannot return more than one field.


1 Answers

You will have to do a row by row compare and copy. What you are attempting to do right now cannot work. You could use INSERT IGNORE INTO site2.events (SELECT * FROM site1.events) if the databases run on the same server and the database user can access both databases. The downside of this, the primary keys would have to be identical or you will miss data.

A better alternative would be to simply have site1 do a callback containing all info for that event to site2 at the moment a new event is added.

like image 69
MueR Avatar answered Nov 02 '22 20:11

MueR