How can a PHP script be used to allow users to select a CSV file from their computer for import into a MySQL table?
To allow users to select a CSV file from their computer for import into a MySQL table, you can create a simple HTML form with a file input field. The PHP script will handle the file upload, read the CSV file, and insert the data into the MySQL table using functions like fopen(), fgetcsv(), and mysqli_query().
<?php
if(isset($_POST['submit'])){
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
while(($data = fgetcsv($handle, 1000, ",")) !== false){
$name = $data[0];
$email = $data[1];
$query = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
mysqli_query($connection, $query);
}
fclose($handle);
echo "CSV file imported successfully!";
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="submit" value="Import CSV">
</form>
Keywords
Related Questions
- How can the getimagesize() function in PHP be used as an alternative method for verifying the content type of an image file?
- What potential pitfalls should be considered when inserting data into a MySQL database using PHP?
- What is the significance of the error "Fatal error: Call to undefined function: gethtml()" in PHP code?