Zend Framework: Proper way to interact with database?

后端 未结 3 1292
孤独总比滥情好
孤独总比滥情好 2021-02-02 02:17

I\'m fairly new to the Zend Framework and MVC and I\'m a bit confused by Zend_DB and the proper way to interact with the database.

I\'m using the PDO MySQL adapter and h

3条回答
  •  渐次进展
    2021-02-02 02:31

    I recommend using the save method.

    //Create a Users Model Object
    $usersDb = new Users();
    
    //Find the record with user_id = 4 and print out their name
    $row = $usersDb->find(4);
    echo $row->first_name . ' ' . $row->last_name
    
    //Change the first name of this user to Brian    
    $row->first_name = 'Brian';
    $row->save();
    
    //Insert a user into the database
    $newUser = $usersDb->fetchNew();
    $newUser->first_name = 'Gilean';
    $newuser->last_name  = 'Smith';
    $newUser->save();
    
    // OR if you get your data from post or any array
    $newUser = $usersDb->fetchNew();
    $newUser->setFromArray($data_from_post);
    $newUser->save();
    

    the reason why i like this approach more is because this why you always have an instance of the user model and you can have custom methods in them ( ex isAdmin ) and also because you might want to ovewrite the save/insert/update function on userRow to do something before they are inserted/updated.

提交回复
热议问题