I want to compare two MySQL tables and to drop columns of table 2 if not in table 1. The code I am using is
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$fields = array();
$fields2 = array();
$dropcols = array();
$res=mysql_query("SHOW COLUMNS FROM table1");
$res2=mysql_query("SHOW COLUMNS FROM table2");
while ($x = mysql_fetch_assoc($res)) {
$fields[] = $x['Field'];
}
while ($x = mysql_fetch_assoc($res2)) {
$fields2[] = $x['Field'];
}
$diff = array_diff($fields2,$fields);
$arraylen = count($diff);
for ($x=0; $x < $arraylen; $x++) {
mysql_query("ALTER TABLE table2 DROP $diff[$x]");
}
Some times the code working and sometimes issue the error undefined offset 0. I don't know where the error is.