I have seen the opencart function which can be used outside with html like
<?php
foreach ($categories as $category){
echo $category['image'];
}
?>
i would like to make a function like that in php which i can grab data from database and use it outside. may be it's an array so foreach statement is working on it.
like i have name and age in my database i would like to use it like this
<?php
foreach($peoples as $people){
echo $people['name'];
echo $people['age'];
}
?>
Thanks in advance
As Aman Chhabra mentioned, you must first fetch the result from database and then you can use foreach
loop to iterate over it. One thing I would like to mention is DON'T use mysql_query()
as use of it is discouraged as per the new guidelines of php development (Check: http://ca1.php.net/manual/en/function.mysql-query.php). To have a compatible code with advanced php use mysqli_query()
instead. Following is the code example utilizing mysqli class. This is procedural way but you can use it in OOP style as well.
//Connect to database
$host = "localhost"; //Change according to yours
$username = "root"; //Change according to yours
$password = ""; //Change according to yours
$database = "test"; //Change according to yours
$con = mysqli_connect($host,$username,$password,$database); //Create the connection
if(!$con)
{
echo "Not connected";
}
else
{
echo "Connected<br />";
}
//Prepare the query to fetch the database records
$query = "select * from TableName"; //Replace the table name with yours
$sql = mysqli_query($con,$query); //Execute the query
while($result = mysqli_fetch_assoc($sql)) //Loop through, till there are records corresponding to the query
{
$rows[] = $result; //Store all the records in an array
}
//Now iterate over each property using foreach loop
foreach($rows as $row)
{
echo "Name - ".$row['name']." Age - ".$row['age']."<br />";
}
Opencart modifies it to the array of results and the use it using foreach
You need to do it like this
$result = mysql_query($con,"SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
{
$data[] = $result;
}
And then later you can use it like this
foreach($data as $row)
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}