The foreach loop is used for arrays. If you want to fetch data from the MYSQL database and want to store a column or multiple columns (put) in the new array then you should declare an array outside the foreach loop .
Fetching data from the database and saving in an array using foreach loop -
First of all, create an MYSQL database table using the below query -
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`title` varchar(255) DEFAULT NULL,
`price` double NOT NULL
);
Insert some data using the below query -
INSERT INTO `products` (`id`, `title`, `price`) VALUES
(1, 'Mobile Phone Xyz', 12000),
(2, 'Laptop 5i', 90000),
(3, 'Tablet 8 GB ', 22999);
If you want to fetch data from the database then create a connection file. We will use a PHP PDO connection.
Create a file config.php .
config.php
<?php session_start();
$databaseHost='localhost';
$databaseUser='root';
$databasePassword='';
$databaseName='tute';
try {
$conn = new PDO("mysql:host=".$databaseHost.";dbname=".$databaseName, $databaseUser, $databasePassword);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'PDO Connected Successfully';
} catch(PDOException $error) {
//echo "Something went wrong " . $error->getMessage();
}
?>
Now, we will fetch the table data using the query and will save table column data in a new array using the foreach loop in PHP.
Create a file index.php .
index.php
<?php
require_once('config.php');
$stmt = $conn->query('SELECT * FROM products ORDER BY id DESC');
$rows=$stmt->fetchAll();
$prices=array();
foreach($rows as $row) {
echo $row['title'].'<br>';
//Save data in an array using foreach loop
$prices[]=$row['price'];
}
echo var_dump($prices);
// $prices is a new array
?>
As you can see in the above code, we declared a new array before the foreach loop and used it inside the foreach loop to save price values one by one using the loop.
You can use this new array after the foreach loop.
In this way, you can fetch data from the database and put it in a new array using a foreach loop.