PHP is a widely used open source server-side scripting language that can be used to develop web applications, dynamic websites, command line scripts, or other types of applications. In PHP, an array is a commonly used data structure that can store multiple values.
When we need to store data in the database into a PHP array, we need to use the PHP PDO extension to connect to the database and use query statements to extract the data from the database. In this article, we will introduce in detail how to add a database to the array.
Connecting to the database in PHP requires the use of the PDO extension. Below is an example showing how to connect to a MySQL database.
// 数据库连接信息 $host = 'localhost'; $dbname = 'my_db'; $username = 'my_username'; $password = 'my_password'; // 连接数据库 $dbh = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
In the above example, we use the provided hostname, database name, username and password to connect to the MySQL database. We create the connection object ($dbh) using the PDO constructor.
Below we will use an example to query the data in the database and store it in a PHP array.
// 查询语句 $sql = "SELECT * FROM users"; // 执行查询,获取结果 $stmt = $dbh->query($sql); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); // 输出结果 print_r($result);
In the above example, we use the SELECT statement to query all rows in the table named "users". We use $dbh->query($sql) function to execute the query and use $stmt->fetchAll(PDO::FETCH_ASSOC) function to fetch all the results and store them into the results array.
In this section, we will learn how to store query results into a PHP array. Below is a sample code that shows how to store the query results into an array named "users" that contains all user information.
// 查询语句 $sql = "SELECT * FROM users"; // 执行查询,获取结果 $stmt = $dbh->query($sql); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); // 创建数组 $users = array(); foreach ($result as $row) { $user = array( 'id' => $row['id'], 'username' => $row['username'], 'email' => $row['email'] ); $users[] = $user; } // 输出结果 print_r($users);
In the above example, we first execute the query and get the results. We then create an array called "users" and iterate over the query results. In each iteration, we create an array called "user" and store each user's information in the array. Finally, we add the "user" array to the "users" array.
This article introduces how to use PDO extension to connect to the MySQL database and store the query results into a PHP array. We also showed how to create an array of user data and populate it with user data in the database. Hope this article is helpful to you.
The above is the detailed content of How to add database to array in php. For more information, please follow other related articles on the PHP Chinese website!