php-mysqlHow to get a key-value array from a MySQL database using PHP?
Using PHP, you can get a key-value array from a MySQL database by executing a query and looping through the results.
$query = "SELECT * FROM table";
$result = mysqli_query($conn, $query);
$array = array();
while ($row = mysqli_fetch_assoc($result)) {
$array[$row['key']] = $row['value'];
}
The output of the above code will be an associative array with the keys and values from the database.
Code explanation
-
$query = "SELECT * FROM table";
- This line creates a query to select all columns from the table. -
$result = mysqli_query($conn, $query);
- This line executes the query and stores the result in the$result
variable. -
$array = array();
- This line creates an empty array to store the key-value pairs. -
while ($row = mysqli_fetch_assoc($result)) {
- This line starts a loop to iterate through the results of the query. -
$array[$row['key']] = $row['value'];
- This line adds the key-value pair from the current row to the array.
Helpful links
More of Php Mysql
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to join tables with PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to count the number of resulting rows in a MySQL database using PHP?
- How to use a MySQL union in PHP?
- How to set a timeout for MySQL query in PHP?
- How to create an SSL connection to MySQL using PHP?
- How to get the last insert ID in PHP MySQL?
- How to fetch data from MySQL in PHP?
See more codes...