Mysql REPLACE INTO table with hundreds of columns

I have a table with hundreds of columns. The table structure is out of my control (controlled by a third party). The table also has horrific field names with spaces, single quotes, etc., as well as table values. The table is updated once per hour through cron. The cron task truncates and rebuilds the table each time. I also save the archive table of this table, I use the REPLACE INTO statement to update or insert as needed.

My task is I don’t want to explicitly define all 350 field names and values ​​and do it again in my REPLACE INTO, since it will take a lot of time and will require maintenance if the table changes. I would prefer to use arrays. This is what doesn’t work, but I hope it gives an idea of ​​the goal (I understand that it is outdated MySQL, but this is for a number of reasons):

$listings = mysql_query("SELECT * FROM current.table");

while ($listing = mysql_fetch_assoc($listings)){

    //prepare variables

    $fields = array_keys($listing);
    $fields = implode('`, `', $fields);
    $fields = "`$fields`";

    $values = array_values($listing);
    $values = implode("`, `", $values);
    $values = "`$values`";

    mysql_query('REPLACE INTO archive.table ($fields) VALUES ($values)');

}
+4
source share
1 answer

Posting as a wiki community cannot arise because of this, as it solved the OP issue (as indicated in the comments).

"Aha! mysql_query . mysql_real_escape_string $ . . ! : - Tavish

mysql_error() . , , , ' , . " .

mysql_query("REPLACE INTO archive.table ($fields) VALUES ($values)");

.

OP ( ):

while ($listing = mysql_fetch_assoc($listings)){ 
    $fields = array_keys($listing); 
    $fields = implode(', ', $fields); 
    $fields = "$fields"; 
    $values = array_values($listing); 
    $values = implode(", ", $values); 
    $values = mysql_real_escape_string($values); 
    $values = str_replace("`","'",$values); 
    $values = "'$values'"; 
    mysql_query("REPLACE INTO archive.table ($fields) VALUES ($values)"); 
} 
+3

Source: https://habr.com/ru/post/1657505/


All Articles