2013-04-03 60 views
-2

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。提前致謝。

+1

你正在談論哪個循環的地方嗎? –

回答

0

這裏是做這件事的一種方法:

$senderInString = implode("','",$senders); 
$senderInString = "('$senderInString')"; 
$newQuery = "SELECT something FROM tables WHERE sender in $senderInString;" 
$newResult = mysql_query($newQuery); 
+0

您還需要進行其他檢查,例如沒有結果等 –

0

使用

 $query= "SELECT IMAGE(S) FROM USER TABLE WHERE USERNAME IN (".implode(',',$senders).")"; 
     $result = mysql_query($query); 

在的foreach