How to pass array into database in php

PHPz
Release: 2023-04-19 10:45:05
Original
555 people have browsed it

In PHP, we often need to store array data in the database so that data can be easily manipulated and managed in subsequent programs. This article will introduce how to pass an array into the database.

First, we need to connect to the database, here is MySQL as an example:

// 连接数据库
$host = 'localhost'; // 数据库服务器地址
$user = 'root'; // 数据库用户名
$pass = 'pass'; // 数据库密码
$dbname = 'mydb'; // 数据库名

$conn = mysqli_connect($host, $user, $pass, $dbname);

if (!$conn) {
    die('Connection failed: ' . mysqli_connect_error());
}
Copy after login

Next, we define a variable containing array data:

$data = array(
    array('name' => 'John', 'age' => 25, 'email' => 'john@example.com'),
    array('name' => 'Alice', 'age' => 30, 'email' => 'alice@example.com'),
);
Copy after login

Then, we can use The loop statement passes the array data into the database one by one:

foreach ($data as $item) {
    $name = mysqli_real_escape_string($conn, $item['name']); // 处理特殊字符
    $age = $item['age'];
    $email = mysqli_real_escape_string($conn, $item['email']);

    $sql = "INSERT INTO users (name, age, email) VALUES ('$name', $age, '$email')";

    if (mysqli_query($conn, $sql)) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
}
Copy after login

Here, we use the mysqli_real_escape_string function to process special characters to prevent SQL injection attacks.

Finally, don’t forget to close the database connection:

mysqli_close($conn);
Copy after login

Through the above steps, you can successfully transfer the array data into the database. In actual development, we can encapsulate these operations into functions or classes to facilitate reuse in multiple programs.

The above is the detailed content of How to pass array into database in php. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!