Better using SQL (PHP)

2. October 2006

There are three forms of using INSERT (mysql manual). I would like to show that form with ‘… SET col_name=”something” …’ is better than others.

public function save() {
    global $CONFIG;
    if(!empty($this->id)) $sql = 'UPDATE `'.$CONFIG['table-users'].'` SET ';
    else $sql = 'INSERT INTO `'.$CONFIG['table-users'].'` SET ';
    
    $sql .='login=\''.mysql_real_escape_string($this->login).'\', ';
    $sql .='pass=\''.mysql_real_escape_string($this->pass).'\' ';    
    
    if(!empty($this->id)) $sql .= 'WHERE id='.intval($this->id);
    
    print $sql;
}

This way you can do update and insert in one function. Whole thing works on column ‘id’ which is primar key and auto_increment in db, its recieved after row is inserted so we can decide if object is new or if it has row in table by having or not having id.

Vlož koment...

Jsou povoleny tyto XHTML tagy: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>





© sh, bw and hosting donated by lidos.cz