SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Thread: Checking

  1. #1
    SitePoint Addict
    Join Date
    Dec 2011
    Posts
    221
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)

    Checking

    Hello! I'm new in php, I studied by my own. I manage to run a simple add, edit,delete. I just downloaded this code and I modified it to have my desired output. I just want to see if I did it right. There is no problem in running, I just want to know if I'm doing right to avoid future errors. I'm new in php oop and pdo.

    here is my code
    Code:
    <?php
    
    class Guitar{
        private $id;   
        private $make;
        private $model;
        private $colour;
        private $price;
        private static $db;
            
        public function __construct($id=null, $make, $model, $colour, $price){
            $this->id     = $id;   
            $this->make   = $make;
            $this->model  = $model;
            $this->colour = $colour;
            $this->price  = $price;
        }
        
        public function id()
    	{
    	return $this->id;
    	}	
    		 
    	public function viewItem($id){
    	
    	$this ->id = $id;
    	$fields = array('id', 'make', 'model', 'colour', 'price');
    	self::conn();
    	
    		try {
            $sql = "SELECT ".implode(',',$fields)." FROM dbo.guitar WHERE id=:id";
            $q = self::$db->prepare($sql);
            $q->execute(array(':id' => $this->id));
            $row = $q->rowCount();
            if ($row == 0)
            {
                echo 'no records found.';
            }
            else
            {
                $results = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,
                "Guitar",$fields);
            }
        }catch (Exception $e){
            print "Error!: " . $e->getMessage();
        }
    		return $results;    
    } 
    	 
    	public function getMake(){
            return $this->make;
        }
         
        public function getModel(){
            return $this->model;
        }
           
        public function getColour(){
            return $this->colour;
        }
           
        public function getPrice(){
            return $this->price;
        }
           
        public function setMake( $make ) {
            $this->make = $make;
        }
           
        public function setModel( $model ){
            $this->model = $model;
        }
           
        public function setColour( $colour ){
            $this->colour = $colour;
        }
           
        public function setPrice( $price ){
            $this->price = $price;
        }
          
        public function save()
        {
            self::conn();
             
        try {
                 
                $data = array('make' =>   $this->make,
    						  'model' =>  $this->model,
                              'colour' => $this->colour,
                              'price' =>  $this->price);
                 
                if($this->id){
                    $sql = "UPDATE guitar SET make=:make, model=:model, colour=:colour, price=:price WHERE id=:id";
                    $data['id'] = $this->id;
                     
                }else{
                    $sql = "INSERT INTO guitar (make,model,colour,price) VALUES (:make,:model,:colour,:price)"; 
    			}
                      
                $q = self::$db->prepare($sql);
                $q->execute($data);
    		
    			
    			echo ''.$q->rowCount().'affected';
                 
        } catch (Exception $e) {
    	
                print "Error!: " . $e->getMessage();
    			
        }
     
        }
         
        public static function getAll(){
            self::conn();
         
    		try{
    			$sql = "SELECT * FROM dbo.guitar WHERE del_stat IS NULL";
    			$q = self::$db->prepare($sql);
    			$q->execute();
    			$row = $q->rowCount();
    				if ($row == 0){
    					echo 'no records found.';
    				}else {
    				$results = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,
                    "Guitar",
                    array('id', 'make', 'model', 'colour', 'price'));
    				}
    		} catch (Exception $e){
            print "Error!: " . $e->getMessage();
    		}
            return $results;    
        }
    
        public function delete(){
         
        self::conn();
         
        try{
             
            $sql = "UPDATE dbo.guitar SET del_stat ='1' WHERE id=:id";
             
            $q = self::$db->prepare($sql);
            $q->bindValue(':id', $this->id, PDO::PARAM_INT);
            $q->execute();
    		echo $q->rowCount().'deleted';
         
        } catch (Exception $e){
            print "Error!: " . $e->getMessage();
        }
        }
         
          
        public static function conn(){
                                  
            if (!self::$db instanceof PDO){
                          
           
                $dsn      = "sqlsrv:myserver; Database=test";
                      
                try {
            
                    self::$db = new PDO($dsn);
                    self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
              
                } catch (PDOException $e) {
                    print "Error!: " . $e->getMessage();
                }
                              
            }
        }
    }
    ?>

    I really need your advice. THANK YOU!

  2. #2
    SitePoint Addict bronze trophy vectorialpx's Avatar
    Join Date
    Dec 2012
    Location
    Bucharest
    Posts
    219
    Mentioned
    7 Post(s)
    Tagged
    0 Thread(s)
    A good friend of mine said once "If it's not broken, don't fix it!"

    First, I hate the indentation and also the practice with variables added in the constructor just to fill some variable-members.
    Instead of [ $id=null, $make, $model, $colour, $price ] you could just have $OPTIONS with default values for your elements. Something like:
    Code:
     <?php
    
    class Guitar {
    
        private $id;   
        private $make;
        private $model;
        private $colour;
        private $price;
        private static $db;
            
        public function __construct($SETTINGS){
    		$allowedKeys = array( 'id', 'make', 'model', 'color', 'price' );
    		foreach( $SETTINGS as $k => $v ) {
    			if(in_array($k, $allowedKeys)) {
    				$this->{$k} = $v;
    			}
    		}
    
    		....
    
    	}
    	
    }
    Instead of getModel and getMake and [...] you can use the __get() magic function and also for set you can use __set() - check http://php.net/manual/en/language.oo...php#object.get
    I can see that you use PDO, witch is a good practice.

    Now, about the functionality, you're the only one that knows what's better.

    Good luck!

  3. #3
    SitePoint Addict
    Join Date
    Dec 2011
    Posts
    221
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    Where can I learn those things. I wish I know that parameters in __construct. Look so cool. Thank you dude! I'm learning..

  4. #4
    SitePoint Addict bronze trophy vectorialpx's Avatar
    Join Date
    Dec 2012
    Location
    Bucharest
    Posts
    219
    Mentioned
    7 Post(s)
    Tagged
    0 Thread(s)
    Most of the things you learn by experience. Create your own projects and also start a
    small freelancing career on different sites, even working on nothing, and you'll get experience.

    As a theoretical knowledge, there are lots of books and documentation over the internet.
    All you need is to want to learn! You may also learn some OOP in school but the real world it's
    a bit different. You have to think OOP, without thinking at a class as a bunch of functions.

    So, there are more ways of typing a variable
    Code:
    <?php
    $mike = 1;
    ${'mike'} = 1;
    and alos
    $_tmp = 'mike';
    $$_tmp = 1;
    
    // keep in mind that if
    $name = '123';
    // 123 is not a valid var name, but:
    $$name = '456';
    // you can make it be
    echo ${’123’};
    // now you can output '456' as "$123" even if this var cannot exist in this form
    ?>
    Good luck!

    PS: don't play to much with this kind of structures because after a wile you may find them unreadable.
    You will not know what you did in your own code so, use them wisely.

  5. #5
    SitePoint Addict
    Join Date
    Dec 2011
    Posts
    221
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    Yes! thanks dude..I came from procedural coding and now I'm looking for a space in oop and pdo.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •