简体   繁体   中英

Why does the loop execute only once?

I have the following small code which manipulate tweets data. I expect my loop to iterate 10 times. However, what happens is that it iterates only once and then exits, with no sign of any error relating to MySQL or otherwise.

$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;

Output :

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

mysqli_fetch_assoc fetches a single row as an associative array where the key is the column name and the value is the column value. The correct way to use it would be to iterate over the result set until the fetch returns NULL , indicating that there are no more rows to fetch:

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

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