How to pass array into database in php
Apr 19, 2023 am 10:05 AMIn 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What Are the Latest PHP Coding Standards and Best Practices?

How Do I Work with PHP Extensions and PECL?

How to Implement message queues (RabbitMQ, Redis) in PHP?

What are the optimization techniques for deduplication of PHP arrays

Can PHP array deduplication take advantage of key name uniqueness?

What are the best practices for deduplication of PHP arrays

Does PHP array deduplication need to be considered for performance losses?

How to Use Reflection to Analyze and Manipulate PHP Code?
