Jump to content

Eliminating duplicated code


NotionCommotion

Recommended Posts

How can I cleanly and efficiently modify the following script so that I do not have to define the empty $user array twice?

 

    public function editRecord(){
        $id=isset($_GET['id'])?$_GET['id']:null;
        if(is_null($id)) {
            $user=array('id'=>0,'firstname'=>'','lastname'=>'','username'=>'','access_id'=>10);
        }
        else {
            $sql='SELECT id,firstname,lastname,username FROM users WHERE id=? AND sites_id=?';
            $stmt = $this->db->prepare($sql);
            $stmt->execute(array($id,$this->site->id));
            if(!$user=$stmt->fetch(PDO::FETCH_ASSOC)){
                $user=array('id'=>0,'firstname'=>'','lastname'=>'','username'=>'','access_id'=>10);
            }
        }
        $this->displayPage(__DIR__.'/templates/editRecord.html',array('user'=>$user,'access'=>$this->getList('access')));
    }

 

Link to comment
https://forums.phpfreaks.com/topic/297647-eliminating-duplicated-code/
Share on other sites

Define the user array at the start of the function. Then overwrite the $user array with the result from the database if one was returned

public function editRecord()
{
    // default user array
    $user=array('id'=>0,'firstname'=>'','lastname'=>'','username'=>'','access_id'=>10);

    $id= isset($_GET['id']) ? $_GET['id'] : null;
    
    if(!is_null($id))
    {
        $sql='SELECT id,firstname,lastname,username FROM users WHERE id=? AND sites_id=?';
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($id,$this->site->id));

        // if query returned a result, override $user array
        if($stmt->numCount() != 0)
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
    }

    $this->displayPage(__DIR__.'/templates/editRecord.html',array('user'=>$user,'access'=>$this->getList('access')));
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.