0

我很困惑为什么第一个结果 0 没有被迭代。有人可以解释为什么并告诉我需要做什么来显示[0]的结果吗?

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/>";?>
4

2 回答 2

1

您可以将 aWHERE 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 个 id,它将创建一个像这样的字符串?, ?, ?, ?,然后我们将其附加到查询中IN ({$placeholder})

使用array_unshift($pieces, implode('', array_fill(0, count($pieces), 'i')));我们创建并附加所有类型作为数组的第一个元素。

于 2013-08-27T23:19:22.890 回答
0

Put query outside of the loop as the commenter Dagon said.

Use a query like this:

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

Then you can send a single query and get all your data at once.

Use $v = implode(',',$pieces); for the contents of IN ().

Using implode should never result in lost array elements.

于 2013-08-27T23:19:04.797 回答