"Zhang San", "Age" => 2"/> "Zhang San", "Age" => 2">
Home >Database >Mysql Tutorial >How does php mysql return query results in the form of an associative array?
1. What is an associative array
Simply put, an array (Array) is a data type that can save multiple data, and each data can be specified by a index to access. Associative Array is a special type of array that stores data in the form of "key" and "value". The index of an associative array is different from that of an ordinary array. It is no longer limited to numbers, but can be strings or numbers that we specify.
In PHP, we can use an associative array to represent it as follows:
$array = array( "姓名" => "张三", "年龄" => 20, "性别" => "男", );
Each element in this array consists of a "key" and a "value" , we can use the key value of the array to access the corresponding value. For example, we can use $array["name"]
to access the name elements in the array.
2. Use mysqli query results to return associative arrays
Below we will learn how to use mysqli to query the database and return the query results in the form of associative arrays.
Connecting to the database
Before using mysqli to perform query operations, we need to establish a database connection first. You can use the following code:
// 建立数据库连接 $mysqli = new mysqli("localhost", "username", "password", "database_name");
where "localhost"
represents the server address where the MySQL database is located, "username"
and "password"
respectively Represents the user name and password, "database_name"
is the name of the database to be connected.
Perform query operation
After connecting to the MySQL database, we must perform a query operation to obtain the required data. In mysqli, you can use the following code to perform database query operations:
// 执行查询操作 $result = $mysqli->query("SELECT * FROM table_name");
where"SELECT * FROM table_name"
is the SQL query statement we need to execute, $result
It is the return value of the query result. *
here means selecting all data.
Processing query results
We can return the mysqli query results as an associative array to facilitate our data operation and display.
// 处理查询结果 $rows = array(); while ($row = $result->fetch_assoc()) { $rows[] = $row; }
In this code, we get one row of data from $result
at a time and convert it into an associative array $row
. After each loop, $row
is added to a $rows
array. Finally, $rows
holds an associative array of all query results.
Close the database connection
After all database operations are completed, we need to close the database connection:
// 关闭数据库连接 $mysqli->close();
The above is the detailed content of How does php mysql return query results in the form of an associative array?. For more information, please follow other related articles on the PHP Chinese website!