How can a foreach loop be used to read an array in PHP and access individual values for database insertion?

When inserting data from an array into a database using PHP, a foreach loop can be used to iterate over the array and access individual values for insertion. Within the foreach loop, each value can be accessed using the current array element, which can then be used in the database insertion query.

// Sample array with data to be inserted into the database
$data = ['John', 'Doe', 'john.doe@example.com'];

// Assuming $conn is the database connection object
foreach ($data as $value) {
    // Escape the value to prevent SQL injection
    $escaped_value = mysqli_real_escape_string($conn, $value);
    
    // Insert the escaped value into the database
    $query = "INSERT INTO users (name) VALUES ('$escaped_value')";
    mysqli_query($conn, $query);
}