D
D
Dmitry2021-08-30 09:45:20
PHP
Dmitry, 2021-08-30 09:45:20

How to delete data in database when importing from CSV?

Good afternoon, dear forum participants. I have a script to import data from CSV to MYSQL database. The script is working and stable. But I need it to DELETE lines that are already in the database before loading data from CSV. Those. the scheme is as follows:
1) Checks if there are rows in the database with the same ID as in the CSV sheet. The ID itself is listed in the first column of the table;
2) If there are such lines, then it deletes them;
3) And then loads all the data from the sheet into the database.

This is needed to update the data in the table by ID / Maybe there is a more correct option .... I don't know.
I would be very grateful - if someone gives advice :)
My code:

set_time_limit(2400);

$mysqli = new mysqli("localhost" , "---" , "---" , "----");

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$table_name= "account";

$csv_file = "2221.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$field_csv = array();
$i = 0;
while (($csv_data = fgetcsv($csvfile, 0, ";")) !== FALSE) {
if($i==0) { $i++; continue; }  // to exclude first line in the csv file.

$field_csv['id'] =mysqli_real_escape_string( $mysqli, $csv_data[0] );  // 1
$field_csv['name'] = mysqli_real_escape_string( $mysqli, $csv_data[1]     ); // 2
$field_csv['tel2'] = mysqli_real_escape_string( $mysqli, $csv_data[2] ); // 3



$query = "INSERT INTO $table_name SET id = '".$field_csv['id']."',name = '".$field_csv['name']."',tel2 = '".$field_csv['tel2']."' ";
mysqli_query($mysqli,$query);

}

fclose($csvfile);

echo "CSV data successfully imported to table!! - OK";

// close connection
$mysqli->close();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Adamos, 2021-08-30
@Dima07-100

Maybe there is a better way....

INSERT ... ON DUPLICATE KEY UPDATE

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question