2013-04-25 41 views
-1

我試圖在查詢中添加默認圖像,如果該文件不存在。 當查詢沒有while循環時,我成功了。但因爲我需要循環這個值。我想將默認圖像添加到查詢中。如果文件不存在,則爲默認圖像mysql pdo

我不會得到任何錯誤,它只是從我的數據庫打印出一些隨機信息。

function fetch_tweets($uid){ 
    $uid = (int)$uid; 
    $query = $this->link->query 
     ("SELECT user.id, user.email, user.username, tweets.message, tweets.date, 
      userdetails.profile_img, userdetails.firstname, userdetails.lastname, 
      following.id, following.user_id, following.follow_id 
    FROM user 
    LEFT JOIN 
     following ON user.id = following.user_id 
    JOIN userdetails ON user.id = userdetails.user_id 
    JOIN tweets ON userdetails.user_id = tweets.user_id 
    WHERE user.id='{$uid}' 
    OR 
      user.id IN (SELECT follow_id 
    FROM following 
    WHERE 
     following.user_id = '{$uid}') 
    GROUP BY tweets.date ORDER BY tweets.date DESC " 
    ); 

    $tweet = array(); 
    while(($row = $query->fetch(PDO::FETCH_ASSOC)) !==FALSE) { 
    $tweet[] = $row; 
    $tweet['profile_img'] = (file_exists("img/{$uid}.jpg")) ? 
    "img/{$uid}.jpg" : "img/default.jpg" ; 

} 
    return $tweet; 
} 
+0

PDO與文件無關。它是一個數據庫驅動程序。 – 2013-04-25 07:59:41

回答

1

您在循環中以錯誤的方式使用變量$ tweet。

下面一行將新元素添加到數組$鳴叫:

$tweet[] = $row; 

及以下線在$鳴叫陣列更新名爲「profile_img」的元素:

$tweet['profile_img'] = "..."; 

但我想,你想要的是這樣的:

while(($row = $query->fetch(PDO::FETCH_ASSOC)) !== FALSE) { 
    // Update the value for profile_img in the row 
    $row['profile_img'] = file_exists("img/{$uid}.jpg") ? "img/{$uid}.jpg" : "img/default.jpg" ; 
    // Add the manipulated row to the $tweet-array 
    $tweet[] = $row; 
} 

請使用類似xde的調試器進行測試錯誤(如果你不熟悉PHP,可能有點複雜),或者只是使用var_dump();.你很快就會發現...

+0

謝謝,我試過了var_dump。但我很新,所以有時候我真的不知道要看什麼。這工作像一個魅力。謝謝你,小夥伴。 – Dymond 2013-04-25 07:27:30

+0

@Dymond但你至少擅長編寫不重要的SQL查詢...... – SimonSimCity 2013-04-25 07:30:08

相關問題