为什么循环只执行一次?

时间:2015-09-21 07:06:58

标签: php mysql mysqli

我有以下操作推文数据的小代码。我希望我的循环迭代10次。但是,会发生的事情是只迭代一次然后退出,没有任何错误迹象与MySQL或其他相关。

$query = "select data from tweets where `screen_name` = 'username' limit 10";
$tweetsq = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
$tweets = mysqli_fetch_assoc($tweetsq);
$tweets_count = mysqli_num_rows($tweetsq);
echo $tweets_count . '<br />'; //See output

$count = 0;
foreach ($tweets as $raw_tweet) {
    $tweet = json_decode($raw_tweet);
    $tweet_id = $tweet->id_str;
    $is_reply = (isset($tweet->in_reply_to_screen_name) && strlen($tweet->in_reply_to_screen_name) > 0) ? 1 : 0;
    $is_retweet = (isset($tweet->retweeted_status) && $tweet->retweeted_status != '') ? 1 : 0;
    $entity_holder = array();
    $has_hashtag = $has_url = $has_mention = $has_media = 0;
    foreach ($tweet->entities as $type => $entity) {
        if (is_array($entity) && count($entity) < 1) {
            //continue;
        } else {
            $entity = array_pop($entity);
            switch ($type) {
                case 'hashtags' : $has_hashtag = 1; break;
                case 'urls' :  $has_url = 1; break;
                case 'user_mentions' : $has_mention = 1; break;
                case 'media' : $has_media = 1; break;
                default :

            }
        }
    }
    echo 'Updating recorde... <br />';
    $query = "UPDATE tweets SET is_reply='" . $is_reply . "' , is_retweet='" . $is_retweet . "', has_hashtag='" . $has_hashtag . "', has_url='" . $has_url . "', has_mention='" . $has_mention . "', has_media='" . $has_media . "' WHERE tweet_id='" . $tweet_id . "'";
    $result = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
    var_dump($result); //See output
    $count++;
    echo '<br />';
}
echo $count;

输出

10 //This is the value of $tweets_count
Updating recorde... 
bool(true) //The result of the UPDATE query
1 //The value of $count at the end of script. It SHOULD be 10

1 个答案:

答案 0 :(得分:1)

mysqli_fetch_assoc单行作为关联数组提取,其中键是列名,值是列值。使用它的正确方法是迭代结果集,直到fetch返回NULL,表明没有更多行要提取:

while ($row = mysqli_fetch_assoc($tweetsq)) {
    $raw_tweet = $row["data"];
    $tweet = json_decode($raw_tweet);
    $tweet_id = $tweet->id_str;
    # etc...