Bala
Bala

Reputation: 1

PHP issues the error undefined offset error

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.

Upvotes: 0

Views: 171

Answers (2)

Barmar
Barmar

Reputation: 782785

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));

Upvotes: 2

Nisanth Sojan
Nisanth Sojan

Reputation: 1099

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

Upvotes: -1

Related Questions