Search code examples
phpdatabasezend-frameworkloopszend-db

Zend Framework: How to insert new data in database by looping through php array


class Model_Core_NodeContents extends Zend_Db_Table_Abstract
{   
    protected $_name = 'node_contents';

    protected $_referenceMap = array(
            "Page" => array(
                    "columns" => array("node_id"),
                    "refTableClass" => "Model_Core_Node",
                    "refColumns" => array("id"),
                    "onDelete" => self::CASCADE,
                    "onUpdate" => self::RESTRICT
                    )
            );

    public function setContent($node_id,$key,$value){
        $select = $this->select()->where("node_id = ?",$node_id)->where($this->_db->quoteInto("`key` = ?",$key));
         echo $select->__toString()."<br />"; 
        $row = $this->fetchRow();
        if($row==false){
            $row = $this->createRow();           
            $row->node_id = $node_id;
            $row->key = $key;
        }
        $row->value = $value;       
        $row->save(); 
        echo $this->_db->lastInsertId();
    }

}

When I call the above code in Loop, only first item of array gets inserted in database.

foreach($data as $key => $value){
    $cnode = new Model_Core_NodeContents();                  
    $cnode->setContent($id, $key, $value);                   
}

$this->_db->lastInsertId(); returns 0 for every data item except the first. Why? How can I insert all the rows of $data array in database by looping?

EDIT

My problem solved. $row = $this->fetchRow(); this line was incorrect. I forgot to add $select in it. Replacing that line with $this->fetchRow($select) solved my problem.


Solution

  • My problem solved. $row = $this->fetchRow(); this line was incorrect. I forgot to add $select in it. Replacing that line with $this->fetchRow($select) solved my problem.