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)');
}
source
share