What are some best practices for reading values from a text file in PHP and storing them in a database?
When reading values from a text file in PHP and storing them in a database, it is important to handle the file reading and database insertion securely and efficiently. One best practice is to use proper error handling to catch any issues that may arise during the process. Additionally, it is recommended to sanitize and validate the data before inserting it into the database to prevent any security vulnerabilities.
<?php
// Open the text file for reading
$file = fopen("data.txt", "r");
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Read data from the text file line by line and insert into the database
while(!feof($file)) {
$line = fgets($file);
$data = explode(",", $line);
// Sanitize and validate data before inserting into the database
$value1 = mysqli_real_escape_string($conn, $data[0]);
$value2 = mysqli_real_escape_string($conn, $data[1]);
$sql = "INSERT INTO table_name (column1, column2) VALUES ('$value1', '$value2')";
if ($conn->query($sql) === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// Close the file and database connection
fclose($file);
$conn->close();
?>