Dominic Kirkwood
Dominic Kirkwood

Reputation: 85

While foreach echo's twice?

just getting to grips with handling foreach loops. For each row, I am setting 'vine' and 'mp4' in $array however when I echo those values they post twice. Here's my code:

$sql="SELECT vine_id,mp4_url FROM videos LIMIT 1";

$res=mysql_query($sql);

while($row=mysql_fetch_assoc($res)){
    foreach ($row as $array) {
        $array=array(
            "vine"=>$row['vine_id'],
            "mp4"=>$row['mp4_url']);
            echo $array["vine"];
            echo $array["mp4"];
     }
}

Here's my output:

bUjdjmFHt5I //vine
https://vines.s3.amazonaws.com/v/videos/2013/04/20/A42066A1-EC83-4211-BA20-DAD287C8AF1E-362-0000002797BBAC52_1.0.7.mp4?versionId=oMGICGs2c7dCbodVIHHiaQ1MhqKg65.y //mp4

bUjdjmFHt5I //vine
https://vines.s3.amazonaws.com/v/videos/2013/04/20/A42066A1-EC83-4211-BA20-DAD287C8AF1E-362-0000002797BBAC52_1.0.7.mp4?versionId=oMGICGs2c7dCbodVIHHiaQ1MhqKg65.y //mp4

Am I missing something in my code that's making this post twice?

Upvotes: 0

Views: 2844

Answers (2)

Sven
Sven

Reputation: 70903

Yes, you are looping over an array that gets instantly destroyed in your code:

$sql="SELECT vine_id,mp4_url FROM videos LIMIT 1";

$res=mysql_query($sql);

Assuming everything went well, you start with $res pointing to a mysql resource that will deliver exactly one result set.

while($row=mysql_fetch_assoc($res)){

You are fetching this result set. $row is now an array with the two keys vine_id and mp4_url.

    foreach ($row as $array) {

Now you are assigning the two keys values to $array, one after another. You have two keys, this loop will run two times.

        $array=array(
            "vine"=>$row['vine_id'],
            "mp4"=>$row['mp4_url']);

Now you destroy the value that gets assigned by foreach and overwrite it with values from $row.

You really only create a copy of the array with slightly different key names.

        echo $array["vine"];
        echo $array["mp4"];

The loop runs twice, the echo occurs twice with the same content.

     }
}

What you really want:

// Use alias in SQL to get the array keys you want
$sql="SELECT vine_id as vine, mp4_url as mp4 FROM videos LIMIT 1";

$res=mysql_query($sql);

// assign the SQL result to a variable of your choice.
while($array=mysql_fetch_assoc($res)){
    // No need to copy the array
    echo $array["vine"];
    echo $array["mp4"];
}

Upvotes: 3

antony
antony

Reputation: 2893

You're looping twice. Try this:

$sql="SELECT vine_id,mp4_url FROM videos LIMIT 1";

$res=mysql_query($sql);

while($row=mysql_fetch_assoc($res)){
    $array = array(
        "vine" => $row['vine_id'],
        "mp4" => $row['mp4_url'],
    );
    echo $array["vine"];
    echo $array["mp4"];
}

Upvotes: 7

Related Questions