Jump to content

Eliminating duplicated code


Go to solution Solved by Ch0cu3r,

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

  • Solution

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')));
}
Edited by Ch0cu3r
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.