2013-08-27 18 views
0

我很困惑,爲什麼第一個結果是0不被迭代。有人可以解釋爲什麼,並告訴我需要做什麼才能顯示[0]的結果?PHP foreach不迭代的第一個結果

Here is my Array: 
array(3) { [0]=> string(3) "390" [1]=> string(3) "377" [2]=> string(3) "382" } 

注意[0]結果沒有通過foreach顯示。最後兩個[1]和[2]顯示正常。

你可以看到這這裏的結果: http://www.rotaryswing.com/swingviewer/videos.php

<?php 
//iterate through video IDS in our DB 
foreach ($pieces as $key => $v) { 

$sql ="SELECT id, video_name, link, phase FROM videos WHERE id=?"; 
    if ($stmt = $mysqli->prepare($sql)) { 
     $stmt->bind_param("i", $v); 

     if ($stmt->execute()) { 
      $stmt->bind_result($id, $vid_name, $vid_link, $phase); 
      while ($stmt->fetch()) { 
       echo "<a style=\"font-size: 14px;\" href='http://www.rotaryswing.com/golf- instruction/video/rst-index.php?cat=$phase&subcat=Rotary%20Swing%20Tour&video=$id&id=$vid_link&name=$vid_name' target=\"blank\">$vid_name</a><br>"; 
      } 
     } 
     else { 
      trigger_error("SQL query failed: " . $stmt->error, E_USER_ERROR); 
     } 
    } 
} 
?> 

當我剛呼應的作品它回聲罰款。循環作爲評議袞之外

<?php echo $pieces[0] . "<br/>";?> 

<?php echo $pieces[1] . "<br/>";?> 

<?php echo $pieces[2] . "<br/>";?> 
+1

我在這裏沒有看到任何錯誤;你確定有一個ID 390的數據庫記錄? –

+2

不要把查詢放在循環中,使用一個查詢然後循環結果 – 2013-08-27 23:13:25

+0

@Jack是的。我認爲0返回false,所以我必須檢查。我認爲。我不知道 –

回答

1

你可以使用一個WHERE IN與陣列:

# create the correct amount of ? 
$placeholder = implode(', ', array_fill(0, count($pieces), '?')); 
$sql ="SELECT id, video_name, link, phase FROM videos WHERE id IN ({$placeholder})"; 
if ($stmt = $mysqli->prepare($sql)) 
{ 
    # add at the begin the type of your array the field types 
    array_unshift($pieces, implode('', array_fill(0, count($pieces), 'i'))); 
    # bind the field type and each value 
    call_user_func_array(array($stmt, 'bind_param'), $pieces); 
    if ($stmt->execute()) 
    { 
     $stmt->bind_result($id, $vid_name, $vid_link, $phase); 
     while ($stmt->fetch()) 
     { 
?> 
<a style="font-size: 14px;" href="http://www.rotaryswing.com/golf-instruction/video/rst-index.php?cat=<?php echo $phase; ?>&subcat=Rotary%20Swing%20Tour&video=<?php echo $id; ?>&id=<?php echo $vid_link; ?>&name=<?php echo $vid_name; ?>" target="blank"><?php echo $vid_name; ?></a><br> 
<?php 
     } 
    } 
    else 
    { 
     trigger_error("SQL query failed: " . $stmt->error, E_USER_ERROR); 
    } 
} 

使用call_user_func_array(array($stmt, 'bind_param'), $pieces);我們綁定每個字段類型和參數的bind_param

使用$placeholder = implode(', ', array_fill(0, count($pieces), '?'));我們創建的字符串與$pieces有佔位符的正確的量,所以如果$pieces有4個IDS會造成這樣?, ?, ?, ?一個字符串,然後我們在IN ({$placeholder})

的查詢中追加使用array_unshift($pieces, implode('', array_fill(0, count($pieces), 'i')));我們創造並將所有類型追加爲數組的第一個元素。

0

認沽查詢說。

使用這樣的查詢:

SELECT id, video_name, link, phase FROM videos WHERE id IN (?)

然後你可以一次發送一個查詢和您的所有數據。對於IN()的內容,使用$v = implode(',',$pieces);

使用implode不應該導致丟失數組元素。