Hie。我試圖不在循環內放置SQL查詢,因爲這會提高性能。我認爲我應該使用內爆。但無法弄清楚如何去做。這裏是我的代碼:如何用循環外的數組查詢數據庫
<?php
//FUNCTION CONNECTNG TO DB HERE
function turn_result_to_array($result)
{
$result_array = array();
for ($count=0; $row = mysql_fetch_array($result); $count++)
{
$result_array[$count] = $row;
}
return $result_array;
}
function get_sender_username()
{
//connect to DB
$query = sprintf("SELECT DISTINCT sender FROM direct_messages
WHERE receiver_username='%s'
ORDER BY direct_messages.id DESC",
mysql_real_escape_string($_COOKIE['username']));
$result = mysql_query($query);
$result = turn_result_to_array($result);
return $result;
}
$senders = get_sender_username();
foreach($senders as $sender)
{ //SELECT IMAGE(S) FROM USER TABLE WHERE USERNAME = $SENDERS }
而不是把查詢的FOREACH裏面的,我想以後把它,所以我不作多次往返到數據庫。僅供參考,我已經知道我們應該改用PDO。提前致謝。
你正在談論哪個循環的地方嗎? –