PHP MYSQL将AUTO INCREMENT设置为MAX + 1

I have a PHP file that inserts data from a CSV file into the MYSQL DB using the LOAD DATA INFILE sql function.

If the CSV data is a duplicate it is not inserted because of the DB table indexing rules (unique).

$sql = "LOAD DATA LOW_PRIORITY LOCAL INFILE 
       '" . $makes_file . "' IGNORE 
       INTO TABLE make 
       FIELDS TERMINATED BY ',' 
       LINES TERMINATED BY '
' (make, img_url)";

$link->query($sql) or die(mysqli_error($link));

For some reason the Auto Increment of the table is not correct from this process.

So I have used the following code to correct this.

$get_max = $link->query("SELECT max(id) as max FROM `make` LIMIT 1");
while ($r = $get_max->fetch_assoc()) {
    $link->query("ALTER TABLE  `make` AUTO_INCREMENT = " . ($r['max'] + 1)) or 
    die(mysqli_error($link));
}

So if anybody knows:

  1. Why the Auto Increment is incorrect from the LOAD DATA sql or
  2. If there is a 'prettier' way to set the auto increment to the max(id) +1

Thanks

This answer is about a prettier way to set the auto increment to the max(id) +1, You can do this with one Query only :

$link->query("ALTER TABLE  `make` AUTO_INCREMENT = ( SELECT max(id)+1 FROM `make` LIMIT 1 )" );

But your first solution should work if AUTO_INCREMENT is unique , check your database sheme

For MyISAM tables you can just set AUTO_INCREMENT to 0 and MySQL will use the current maximum value plus one.

$link->query('ALTER TABLE make AUTO_INCREMENT = 0');

From the docs:

You cannot reset the counter to a value less than or equal to any that have already been used. For MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum plus one.