Diego Piffaretti Diego Piffaretti - 3 months ago 10
PHP Question

Foreach Insert Multiple values SQL SERVER

i have an application that monitors TWITTER. i have the following code:

PS: I have a VAR $Tweets receiving content from twitter , after, starts the code:

foreach ($tweets->statuses as $key => $tweet) {
$image=$tweet->user->profile_image_url;
$user=$tweet->user->screen_name;
$name=$tweet->user->name;
$data=$tweet->created_at;
$post=$tweet->text;

echo "$image $user $name $data $post" ;
echo "<br>";
}


It Works PERFECT! It prints many rows. :)

When i try to insert it in my SQL Server, the problem starts:

$insert = "INSERT INTO dbo.twitter (user_photo, user_name, name, post, data) VALUES ('$image', '$user', '$name', '$post', '$data')";


$result=sqlsrv_query($conn, $insert);

if (!$result) {
print("Error");
} else {
print("Data Inserted!");

mssql_close($conn); }


When i run the above command, it insert ONLY 1 row data!!! Why??? If i try print it with "echo", it print many rows, but when i make a insert, it insert only one row! Can someone help me?

Answer

You need to make sure it executes within the loop. So

foreach ($tweets->statuses as $key => $tweet) { 
    $image=$tweet->user->profile_image_url;
    $user=$tweet->user->screen_name;
    $name=$tweet->user->name;
    $data=$tweet->created_at;
    $post=$tweet->text;

    echo "$image $user $name $data $post" ;
    echo "<br>"; 

    $insert = "INSERT INTO dbo.twitter (user_photo, user_name, name, post, data) VALUES ('$image', '$user', '$name', '$post', '$data')";


    $result=sqlsrv_query($conn, $insert);  
}