southbeach
Programmer
Working on a script to backup all tables w/in one DB to another DB - They have different names but their tables' name are identical.
This is what I have:
The [$insert] string is built with correct syntax. All I need to add is
(a) Open 2nd DB
(b) Execute query to insert the records
Not having done this before forced me to stop and think if this would be wise since the tables share the same names. I am working within a loop and I am afraid that the script will crash since it will not know which DB to access once they are both opened.
My idea to solve this is to store all the [$insert] strings within an array and then once the construct loop is finished, loop through the [$insert] array and run all the insert queries.
What do you guys think?
Thanks!
This is what I have:
Code:
<?
$conn = mysql_connect('localhost', 'userID', 'PassWord');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('MyDB_Name');
$tables = mysql_query("show tables");
echo '<table width="100%" border="1"><tr><th>File Processed</th><th>Time Processed</th></tr>';
while ($tlist = mysql_fetch_array($tables)) {
echo '<tr><td>' . $tlist[0] . '</td><td>' . date() . '</td></tr>';
$qstr = 'select * from ' . $tlist[0];
$result = mysql_query($qstr);
if (!$result) {
die('Query failed: ' . mysql_error());
}
while ($rows = mysql_fetch_assoc($result)) {
$i = 0;
$insert = 'INSERT INTO `' . $tlist[0] . '` ( ';
$lastf = mysql_num_fields($result) - 1;
/* get column metadata */
while ($i < mysql_num_fields($result)) {
// echo "Information for column $i:<br />\n";
$meta = mysql_fetch_field($result, $i);
if (!$meta) {
echo "No information available<br />\n";
}
echo 'i: ' . $i . ' lastf: ' . $lastf . '<br />';
if ($i != $lastf) { $cols .= '`' . $meta->name . '`,'; }
else { $cols .= '`' . $meta->name . '`'; }
if ($i != $lastf) { $vals .= '"' . $rows[$meta->name] . '",'; }
else { $vals .= '"' . $rows[$meta->name] . '"'; }
$i++;
}
$insert .= $cols . ') VALUES (' . $vals . ')';
//echo $insert;
}
}
echo '</table>';
mysql_free_result($result);
?>
The [$insert] string is built with correct syntax. All I need to add is
(a) Open 2nd DB
(b) Execute query to insert the records
Not having done this before forced me to stop and think if this would be wise since the tables share the same names. I am working within a loop and I am afraid that the script will crash since it will not know which DB to access once they are both opened.
My idea to solve this is to store all the [$insert] strings within an array and then once the construct loop is finished, loop through the [$insert] array and run all the insert queries.
What do you guys think?
Thanks!