How can PHP be used to automate the process of adding new entries to a database based on files in a directory?
To automate the process of adding new entries to a database based on files in a directory, you can use PHP to read the files in the directory, extract the necessary information, and insert it into the database. This can be achieved by using functions like scandir() to get a list of files in the directory, parsing the file data, and executing SQL queries to insert the data into the database.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Directory containing files
$directory = "/path/to/directory";
// Get list of files in the directory
$files = scandir($directory);
foreach ($files as $file) {
if (!in_array($file, array(".", ".."))) {
// Process file data and insert into database
$data = file_get_contents($directory . "/" . $file);
$data = json_decode($data, true); // Assuming data is in JSON format
$sql = "INSERT INTO table_name (column1, column2) VALUES ('" . $data['value1'] . "', '" . $data['value2'] . "')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
// Close database connection
$conn->close();
?>