What are some best practices for handling and importing external data into MySQL databases using PHP and Apache?

When handling and importing external data into MySQL databases using PHP and Apache, it is important to sanitize and validate the data to prevent SQL injection attacks and ensure data integrity. One best practice is to use prepared statements with parameterized queries to securely insert data into the database.

// Connect to MySQL 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);
}

// Prepare and bind SQL statement
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);

// Set parameters and execute
$value1 = "value1";
$value2 = "value2";
$stmt->execute();

// Close statement and connection
$stmt->close();
$conn->close();