views:

77

answers:

4

Hi, I want to be able to switch from the current db to multiple dbs though a loop:

$query = mysql_query("SELECT * FROM `linkedin` ORDER BY id", $CON ) or die( mysql_error() );
if( mysql_num_rows( $query ) != 0 ) {
    $last_update = time() / 60;
    while( $rows = mysql_fetch_array( $query ) ) {
        $contacts_db = "NNJN_" . $rows['email'];
        // switch to the contacts db
        mysql_select_db( $contacts_db, $CON );
        $query = mysql_query("SELECT * FROM `linkedin` WHERE token = '" . TOKEN . "'", $CON ) or die( mysql_error() );
        if( mysql_num_rows( $query ) != 0 ) {
            mysql_query("UPDATE `linkedin` SET last_update = '{$last_update}' WHERE token = '" . TOKEN . "'", $CON ) or die( mysql_error() );   
        }else{
            mysql_query("INSERT INTO `linkedin` (email, token, username, online, away, last_update) VALUES ('" . EMAIL . "', '" . TOKEN . "', '" . USERNAME . "', 'true', 'false', '$last_update')", $CON ) or die( mysql_error() );
        }
    }
    mysql_free_result( $query );
}
// switch back to your own
mysql_select_db( USER_DB, $CON );

It does insert and update details from the other databases but it also inserts and edits data from the current users database which I dont want. Any ideas?

+1  A: 

You're probably have wrong database design.

Col. Shrapnel
+1  A: 

one improve that i see is that you can use one query to duplicate or update

the syntax is like :

INSERT INTO mytable (field_list.....) VALUES (values_list...) 
    ON DUPLICATE KEY 
UPDATE field1 = val1 ...
Haim Evgi
+1  A: 

Never use the php mysql_select_db() fundtion - as you've discovered the code (and the coder) gets very confused very quickly.

Explicitly state the DB in the queries:

SELECT * FROM main_database.a_table....

UPDATE alternate_db.a_table SET...

REPLACE INTO third_db.a_table...

C.

symcbean
It's not the answer due to I restarted :-) BUT this seems to be useful information on what I was after so thank you.
Phil Jackson
BTW - looking at the code, I think this could all be done with a couple of SQL statements on the DBMS (using the database_name.table_name construct) without having to pull the data into PHP / using a loop.
symcbean
A: 

you are reassigning $query during your while loop. this will give strange results. use $query2 for the query inside the loop

steelbytes