Home Backend Development PHP Problem How to store array in database in PHP

How to store array in database in PHP

Apr 19, 2023 am 11:38 AM

In PHP programming, arrays are a very commonly used data structure. Data can be conveniently stored and managed through arrays. Storing arrays into the database is also a common operation in daily applications. This article will introduce how to store arrays in the database in PHP.

  1. Connect to the database

Before storing the array, you need to use PHP to connect to the database. Through PHP's mysqli or PDO extension, the connection with databases such as MySQL can be achieved.

First, you need to configure the database connection information in PHP, including host address, user name, password, database name, etc.;

Then, you can use the mysqli_connect() or PDO connect() method , link to the target database.

For example:

//Use mysqli_connect() to connect to the database
$servername = "localhost";
$username = "root";
$password = "123456 ";
$dbname = "test";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {

die("Connection failed: " . mysqli_connect_error());
Copy after login

}

//Use PDO to connect to the database
$dsn = 'mysql:dbname=test;host=localhost';
$user = 'root';
$password = '123456';

try {

$dbh = new PDO($dsn, $user, $password);
Copy after login

} catch (PDOException $e) {

echo 'Connection failed: ' . $e->getMessage();
Copy after login

}

  1. Create data table

Next, in the target database, you need to first create a data table to store the array. You can use the MySQL command line or visualization tools to create a table containing the data that needs to be stored.

For example: Suppose you need to store an array of student information, including student ID, name and age, you can create the following data table:

CREATE TABLE students (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(20) NOT NULL DEFAULT '',
age int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  1. Storage array

Next, you can insert the PHP array data into the data table. You can use the MySQL INSERT command or the function provided by PHP to perform the insert operation to insert the array into the target data table.

For example: to insert an array containing three student information into the above data table, you can use the following code:

//An array containing three student information
$ students = array(
array('name' => 'Zhang San', 'age' => 18),
array('name' => '李思', 'age' => ; 19),
array('name' => '王五', 'age' => 20)
);

//Loop through the array and add each student's information Insert into data table
foreach ($students as $student) {
$name = $student['name'];
$age = $student['age'];

/ /Use mysqli to implement
$sql = "INSERT INTO students (name, age) VALUES ('$name', $age)";
if (mysqli_query($conn, $sql)) {

echo "New record created successfully";
Copy after login

} else {

echo "Error: " . $sql . "<br>" . mysqli_error($conn);
Copy after login

}

//Use PDO to implement
$stmt = $dbh->prepare("INSERT INTO students (name, age) VALUES (: name, :age)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':age', $age);
$ stmt->execute();
}

  1. Query data

After storing the array in the database, you can also query the data through the MySQL command line or PHP code data in the table. You can use the SELECT command or the query operation function provided by PHP to query the data table.

For example: to query all student information contained in the data table, you can use the following code:

//Use mysqli to implement
$sql = "SELECT * FROM students";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {

echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>";
Copy after login

}
} else {
echo "0 results";
}

//Use PDO to implement
$stmt = $dbh->prepare("SELECT * FROM students") ;
$stmt->execute();
$res = $stmt->fetchAll();
if (count($res) > 0) {
foreach ($res as $row) {

echo "id: " . $row['id'] . " - Name: " . $row['name'] . " - Age: " . $row['age'] . "<br>";
Copy after login

}
} else {
echo "0 results";
}

Summary

In PHP programming, Storing an array into a database is a very common operation. The array can be inserted into the target data table through the MySQL INSERT command or the function provided by PHP to perform the insert operation. At the same time, you can also query the data table through the SELECT command of MySQL or the query operation function provided by PHP. This method makes it easy to store and manage data, and is also an inevitable operation in daily work.

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1276
29
C# Tutorial
1256
24