Home  >  Article  >  Backend Development  >  How to store array in database in PHP

How to store array in database in PHP

PHPz
PHPzOriginal
2023-04-19 11:38:181019browse

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

}

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

try {

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

} catch (PDOException $e) {

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

}

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

} else {

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

}

//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>";

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

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