开发者

DB query in for loop errors on second loop (PHP, Codeigniter)

A simple loop loops through an array and deletes database records...

Controller:

foreach ($deletedTags as $deletedTag) {
    $tagId = $this->tags_model->get_tag_id($deletedTag);
    $this->tags_model->delete_tag_association_by_tag($workId, $tagId);  
}

$deletedTags is an array, an example being:

Array ( [0] => purple [1] => trees [2] => green ) 

Model:

function get_tag_id($tag) {
    $this->db->where('tags.name',开发者_JS百科 $tag);
    $query = $this->db->get(self::TABLE);
    return $query->row()->id;
}

When there is only one value in $deletedTags it works fine. When there's more than one value the model function get_tag_id($tag) breaks on the second loop. It errors on the line return $query->row()->id; with:

Undefined property: stdClass::$id

Any idea why?


I've solved it. For some reason it's erroring because it can only find the first tag in the array in the db (even though the other tags do exist in the db). I added a tag_exists check and all is fine...

foreach ($deletedTags as $deletedTag) {
    if ($this->tags_model->tag_exists($deletedTag)) {
        $tagId = $this->tags_model->get_tag_id($deletedTag);
        $this->tags_model->delete_tag_association_by_tag($workId, $tagId);
    }
}

Weird.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜