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
- Are there any recommended PHP libraries or tools for parsing and manipulating HTML content, specifically for tasks like filtering out iFrames?
- What other encryption functions besides md5() and crypt() are recommended for password security in PHP?
- What are the potential pitfalls when using $_POST["var"] or $HTTP_POST_VARS["var"] to read form data in PHP?