设置post_tag所有帖子

I'm trying to add post_tag to my posts in WordPress.

...

$tag = array('tag1', 'tag2', 'tag3', 'tag4', 'tag5'); // many tag

$query_post = "SELECT * FROM wp_posts WHERE post_status='publish' LIMIT 1000";
$result_post = mysql_query($query_post);
while($row_post = mysql_fetch_array($result_post)){
$post_id = $row_post[ID];
$newtag = "";
for ($i=1; $i<=5; $i++) {
$tag = $tag[rand(0, 4)]);
$newtag .= $tag . ",";
}
wp_set_post_terms($post_id, $newtag, 'post_tag', true);
}

...

every time I run a script (for example, in a background: php tag.php >1.log 2>1.log &) I get an error: [8950772.542355] Out of memory: Kill process 32701 (php) score 156 or sacrifice child.

I increased memory_limit in php.ini on 2G, but this does not solve the problem (. What can be wrong with this simple script?

UPDATE: ok, guys. I changed the code, now it looks like this: ...

$query_post = "SELECT * FROM wp_posts WHERE post_status='publish' LIMIT 1000";
if (!$result_post = $mysqli->query($query_post)) {  exit; }
while ($row_post = $result_post->fetch_assoc()) {
    $post_id = $row_post[ID];
    for ($i=1; $i<=5; $i++) {
        $tag = str_replace("Tag", $episode_name, $tag_episode_1[rand(0, 106)]);
        $newtag .= $tag . ",";
    }   
    wp_set_post_terms($post_id, $newtag, 'post_tag', true);     
}

...

Out of memory: Kill process 32701 (php) score 156