Skip to content
PHP Logo

How can data from a database be assigned to a one-dimensional array in PHP?

To assign data from a database to a one-dimensional array in PHP, you can fetch the data from the database using a query, loop through the results, and store each row in the array. This can be achieved using functions like mysqli_fetch_assoc() or PDO fetch() to fetch rows from the result set and store them in the array.

php
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Query to fetch data from the database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Initialize an empty array to store the data
$dataArray = array();

// Loop through the results and store each row in the array
while ($row = mysqli_fetch_assoc($result)) {
    $dataArray[] = $row;
}

// Close the connection
mysqli_close($connection);

// Now $dataArray contains the data from the database in a one-dimensional array