0

I have 2 seperate databases with the same structure. I want to move a selected set of rows from one table to another. I am using PDO to select all the rows, then in a while loop I am assuming that I can insert each row into the new table then delete it from the old table.

With normal mysql this is quite a simple task, but I want to use namespaces so that I can easily modify the table structure ect. I have the following working but it does not move the entry to the new table:

 try {
        $sql = "SELECT * FROM `calls` WHERE `calls`.`status`=0 AND `calls`.`stage` < 4 AND `calls`.`answer` < (NOW() - INTERVAL 10 MINUTE)";
        $query = $this->staging->query($sql);
        while($row = $query->fetch(PDO::FETCH_ASSOC)) {
            $sql = "INSERT INTO `table` (`field1`,`field2`) VALUES (?,?)";
            $query = $this->production->prepare($sql);
            $query->execute($array);
        }
    }
    catch(PDOException $e) {
        $this->informer("FATAL", "Unable to process broken IVR surveys. Error: ".$e->getMessage());
    }
1
  • Where does $array come from?
    – xdazz
    Jun 18, 2012 at 9:36

3 Answers 3

4

You can do it without a while:

INSERT INTO db1.table (fields) SELECT fields FROM db2.table

Of course both databases must be on the same machine

3
  • That's of course assuming they're on the same server, but if so, this is the obviously best solution.
    – deceze
    Jun 18, 2012 at 9:38
  • different servers unfortunately
    – mauzilla
    Jun 18, 2012 at 9:48
  • @dynamic - I have a situation where I can use this. Is it possible to execute this kind of query using PHP PDO? My understanding of PDO is that the PDO object requires a DB to be specified when instantiating the statement handler. E.g. new PDO("mysql:host=localhost;dbname=mydb", 'someuser', 'somepass') - how can we achieve a data transfer between 2 DBs on the same server using PDO?
    – Adam
    Aug 19, 2014 at 17:26
0

It likely does not work because you are using the question mark placeholder style in the prepared statement, but are passing a named array to execute.

If you name the parameters instead, it should work:

$sql = "INSERT INTO `table` (`field1`,`field2`) VALUES (:field1, :field2)";
0

Another approach is using federated tables in MySQL to do what you're trying to do. There are some limitations.... but here are the docs to get you going...

http://dev.mysql.com/doc/refman/5.0/en/federated-use.html http://dev.mysql.com/doc/refman/5.0/en/federated-limitations.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.