How can PHP be used to extract specific information from a text file and store it in a database?
To extract specific information from a text file and store it in a database using PHP, you can read the text file line by line, parse the data to extract the desired information, and then insert it into the database using SQL queries.
<?php
// Open the text file for reading
$file = fopen("data.txt", "r");
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Read the file line by line
while(!feof($file)) {
$line = fgets($file);
// Parse the line to extract specific information
$data = explode(",", $line);
$name = $data[0];
$age = $data[1];
// Insert the extracted information into the database
$sql = "INSERT INTO table_name (name, age) VALUES ('$name', '$age')";
$conn->query($sql);
}
// Close the file and database connection
fclose($file);
$conn->close();
?>
Keywords
Related Questions
- What are the potential pitfalls of relying solely on client-side validation for form inputs in PHP, especially when dealing with sensitive data like email addresses?
- How can the issue of data being saved as "0" in a database be resolved in PHP?
- What are the advantages of using named parameters over question marks in prepared statements in PHP?