What are some best practices for saving extracted data from a webpage into a database using PHP?
When saving extracted data from a webpage into a database using PHP, it is important to sanitize the data to prevent SQL injection attacks. It is also recommended to use prepared statements to securely insert the data into the database. Additionally, consider setting up error handling to catch any potential issues during the data insertion process.
// Assuming $extractedData contains the extracted data from the webpage
// Establish a database connection
$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);
}
// Prepare and bind the SQL statement
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $extractedData['value1'], $extractedData['value2']);
// Execute the statement
$stmt->execute();
// Check for errors
if ($stmt->error) {
echo "Error: " . $stmt->error;
} else {
echo "Data inserted successfully";
}
// Close the statement and connection
$stmt->close();
$conn->close();