How can PHP be used to read and process data from a file and then write it to a MySQL database?
To read and process data from a file and then write it to a MySQL database using PHP, you can first read the contents of the file using file_get_contents() or fopen(), process the data as needed, and then insert it into the MySQL database using MySQLi or PDO.
<?php
// Read file contents
$fileContents = file_get_contents('data.txt');
// Process data as needed
$processedData = processData($fileContents);
// Connect to MySQL database
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
// Insert processed data into database
$stmt = $mysqli->prepare("INSERT INTO table_name (column_name) VALUES (?)");
$stmt->bind_param('s', $processedData);
$stmt->execute();
// Close statement and connection
$stmt->close();
$mysqli->close();
function processData($data) {
// Process data here
return $data;
}
?>
Related Questions
- In the PHP script provided, what are some best practices for handling file deletion operations to avoid errors?
- What are the potential pitfalls of using mysqli_real_escape_string for handling NULL values in PHP MySQL queries?
- What is the best practice for counting between two specific numbers in PHP?