First thing to point out is that mysqli_query()'s first argument is you need to feed it with a mysqli connection.
Second, you do not need another foreach loop. Just push the values inside the while and then finally in the end return that value container.
function gettradinghours($storeid){
// 1st point! connection!
$connection = mysqli_connect('localhost', 'username', 'password', 'database_base');
$select_tradinghours = mysqli_query($connection, "SELECT * FROM `tradinghours` WHERE `storeid`='54' ORDER BY FIELD(openday, 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY')");
$atradinghours = array();
// no need for that array push thing, just push it normally and return in the end
while($fetch_tradinghours = mysqli_fetch_array($select_tradinghours)){
$atradinghours[] = $fetch_tradinghours['openday']. ' ' .$fetch_tradinghours['starttime']. ' - ' .$fetch_tradinghours['endtime'];
}
return $atradinghours; // return the gathered/pushed values
}
print_r(gettradinghours("54")); // use the function
- Lastly your parameter that you feed inside your function is not used. And use prepared statements instead.
function gettradinghours($storeid){
// connection!
$connection = mysqli_connect('localhost', 'username', 'password', 'database_base');
// use prepared statements!
$stmt = $connection->prepare("
SELECT openday, starttime, endtime FROM `tradinghours` WHERE`storeid` = ?
ORDER BY FIELD(openday, 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY')
");
$stmt->bind_param('i', $storeid); // bind the paramter input!
$stmt->execute();
$stmt->bind_result($openday, $starttime, $endtime);
$atradinghours = array();
while($stmt->fetch()) { // as usual push the values
$atradinghours[] = $openday. ' ' .$starttime. ' - ' .$endtime;
}
return $atradinghours; // return the gathered values
}
print_r(gettradinghours(54));
Sidenote:
If you do not want such result (an array) you could build a string instead:
$atradinghours = '';
while($stmt->fetch()) { // as usual push the values
$atradinghours .= $openday. ' ' .$starttime. ' - ' .$endtime . '<br/>';
}
Then in the end, you could now echo properly a string:
echo gettradinghours(54);