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


<?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!

A good friend of mine said once “If it’s not broken, don’t fix it!”

First, I hate the indentation :slight_smile: 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:

 <?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.oop5.overloading.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!

Where can I learn those things. I wish I know that parameters in __construct. Look so cool. Thank you dude! I’m learning…

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. :wink:

So, there are more ways of typing a variable

<?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 ${&#8217;123&#8217;};
// 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.

Yes! thanks dude…I came from procedural coding and now I’m looking for a space in oop and pdo.