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
- 最後不使用你的參數,你自己的函數中覓食。並使用準備好的語句。
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));
旁註:
如果你不希望這樣的結果(數組),你可以建立一個字符串,而不是:到底
$atradinghours = '';
while($stmt->fetch()) { // as usual push the values
$atradinghours .= $openday. ' ' .$starttime. ' - ' .$endtime . '<br/>';
}
然後,你現在可以回聲正確一個字符串:
echo gettradinghours(54);
是的,你是在foreach循環完成後返回值,所以它重新在$ atradinghours數組轉換最後一個值 – Choco 2014-10-31 11:32:59
@ lock,我發佈了您的問題的答案,您只需在$ getval的forloop中添加括號即可。所以它會是$ getval []而不是$ getval並且您的問題將得到解決。 – 2014-10-31 11:34:56