简体   繁体   中英

Php loop through array with key value pair and save to database

I have an array $s which stores incoming data from a JSON feed. The format of the array is like this:

     $s = array("tweets"=>1, "likes"=>4, "plusones"=>7);

How would I loop through the array: $s , and pick the values of the keys so that I can then assign to the variables $tweets, $likes and $plusones.

This was what I did but I'm not able to extract the values and store them in the variables I've set to nil

   foreach($social_shares as $social_share=>$include){
     echo $social_share . ": " . $include . "<br>";
        $tweets = nil;
        $likes = nil;
        $plusones = nil;

   $sql4 = mysql_query("INSERT INTO social_shares(article_id, tweets, likes, plusones ) VALUES ($s -> article_id ,'$tweets', '$likes', '$plusones')");
    }

Now we're talking. The first question didn't show any effort from your part. However, I need to tell you that this is PHP arrays 101 . You can simply do:

$tweets = $social_shares['tweets'];
$likes = $social_shares['likes'];
$plusones = $social_shares['plusones'];

However, you cannot use SQL like that. You are vulnerable to SQL injection . Please read over this thread to see possible solutions:

How can I prevent SQL injection in PHP?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM