0

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.

2
  • Thank you Barmar, Worked like a charm. I am a beginner in programming. Commented Nov 16, 2013 at 12:13
  • Excuseme Barmar for bothering u. Could u explain the usage of foreach(..) , $diff = array_values(..). Or Direct me to a link to study these in details if possible. Thank u. Commented Nov 16, 2013 at 12:24

2 Answers 2

2

array_diff doesn't reindex the elements of the resulting array, they keep their indexes from fields, so there are gaps in the index. Use foreach to loop through the array values regardless of the indexes.

foreach ($diff as $column) {
    mysql_query(  "ALTER TABLE table2   DROP  $column");
}

Or you can do:

$diff = array_values(array_diff($fields2, $fields));
Sign up to request clarification or add additional context in comments.

Comments

-1

it is becouse sometimes the array $diff will not contain any values

1 Comment

In that case $arraylen will be zero and the loop won't do anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.