Home  >  Article  >  Backend Development  >  How to pass array into database in php

How to pass array into database in php

PHPz
PHPzOriginal
2023-04-19 10:05:16652browse

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());
}

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'),
);

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);
    }
}

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);

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!

Statement:
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