insert array into sql in php

To insert an array into an SQL database using PHP, you can use prepared statements. Here's an example of how you can do it:

main.php
// Assuming you have an array of data
$data = array('John Doe', 25, 'john@example.com');

// Connect to the database
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $dbh = new PDO($dsn, $username, $password);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

// Prepare the insert statement
$stmt = $dbh->prepare("INSERT INTO users (name, age, email) VALUES (?, ?, ?)");

// Bind the array values to the statement placeholders
$stmt->bindParam(1, $data[0]);
$stmt->bindParam(2, $data[1]);
$stmt->bindParam(3, $data[2]);

// Execute the statement
$stmt->execute();
655 chars
25 lines

In this example, we assume you have a database table called "users" with columns "name", "age", and "email". The $data array contains the values you want to insert into these columns. The statement placeholders ? are used to safely bind the values from the array to the SQL statement.

related categories

gistlibby LogSnag