P粉8173547832023-08-29 00:13:45
First, you need to read and discard the header row in the CSV. Then, using appropriate, prepared, and parameterized queries, you can update the database correctly. Since the dates in the .csv file are in the correct format, no action is required, but this may not be the case with other CSV files, and often the dates will need to be reformatted before they can be stored correctly into the table.
<?php //index.php $connect = mysqli_connect("localhost", "root", "1234", "ml_database"); $message = ''; if(isset($_POST["upload"])) { if($_FILES['product_file']['name']) { $filename = explode(".", $_FILES['product_file']['name']); if(end($filename) == "csv") { $handle = fopen($_FILES['product_file']['tmp_name'], "r"); // 读取并忽略标题行 $data = fgetcsv($handle, 1000, ","); // 准备查询一次 $query = "UPDATE my_table SET date = ?, births = ? WHERE data_id = ?"; $stmt = $connect->prepare($query); // 循环遍历csv剩余的行 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $stmt->bind_param('sss', $data[0],$data[1],$data[2]); $stmt->execute(); } fclose($handle); header("location: index.php?updation=1"); exit; // 重定向后一定要使用exit } else { $message = ''; } } else { $message = ''; } }
NOTE: I assume all 3 columns are of type text.
$stmt->bind_param('sss', $data[0],$data[1],$data[2]); ^^^
If date_id
is of type integer, you can change it to 'ssi'
, although 3 s
will usually work fine too.
Reference:
fgetcsv
mysqli_prepare
mysqli_bind_param