php - update if not inserted in yii -


i want update values in table, if values not inserted. here code-

function save_data($date, $game, $score) {     $criteria = new cdbcriteria;     $criteria->addcondition("date = '{$date}'");     $data = array("date" => $date,         "game" => $game,         "score" => $score);     $game_report = new gamereport();     $game_report->attributes = $data;     $game_report->save(); } 

but keeps on inserting duplicate values though have provided date condition. why? how update , not insert duplicate values?

in order make update, need on loaded database model. in case, can done as:

function save_data($date, $game, $score) {     $criteria = new cdbcriteria;     $criteria->addcondition("date = '{$date}'");      $data = array(         "date" => $date,         "game" => $game,         "score" => $score     );      $game_report = gamereport::model()->findbyattributes($data);     if (empty($game_report)) {         $game_report = new gamereport();     }     $game_report->attributes = $data;     $game_report->save(); } 

also, avoid sql injection, should bind condition params like:

$criteria->addcondition("date = :d"); $criteria->params[':d'] = $date; 

or simply:

$criteria->compare('date', $date); 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -