Home > Article > Backend Development > How to query a column of data in php and put it into an array
In PHP, we often need to query data from the database and store it in an array for subsequent processing. Among them, querying a column of data and putting it into an array is a common requirement.
The following are the steps to achieve this requirement:
Use PHP’s built-in mysqli function to easily connect to the database. First, we need to establish a connection first, using mysqli_connect().
For example:
$conn = mysqli_connect($servername, $username, $password, $dbname);
Among them, $servername represents the MySQL server name, $username represents the user name, $password represents the password, and $dbname represents the database name.
Next, we need to execute the query statement. Use the mysqli_query() function to execute a SQL statement and return a result set.
For example:
$query = mysqli_query($conn, "SELECT column_name FROM table_name");
Among them, $conn represents the connection object, and "SELECT column_name FROM table_name" represents the query statement. In actual applications, column_name and table_name need to be replaced with specific column names and table names.
We can use the while loop statement to iterate through all the results and store them into an array.
For example:
$result = array(); while ($row = mysqli_fetch_assoc($query)) { $result[] = $row['column_name']; }
Among them, $result represents the array storing the results, and $row represents a row of data in the result set. Get the value of column_name from $row and store it in the $result array.
After completing the data query, you should use the mysqli_close() function to disconnect from the database.
For example:
mysqli_close($conn);
Full code example:
$conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("连接失败: " . mysqli_connect_error()); } $query = mysqli_query($conn, "SELECT column_name FROM table_name"); $result = array(); while ($row = mysqli_fetch_assoc($query)) { $result[] = $row['column_name']; } mysqli_close($conn);
At this point, we can query a column through PHP and put it into an array.
Summary:
In PHP, the mysqli function can be used to easily connect to the database. Use the mysqli_query() function to execute a SQL statement, and use the mysqli_fetch_assoc() function to get a row of data from the result set. Finally, all results are stored in an array through a while loop. After the connection is successful, use the mysqli_close() function to disconnect.
The above is the detailed content of How to query a column of data in php and put it into an array. For more information, please follow other related articles on the PHP Chinese website!