1

Can anyone identify what is wrong with this lines of code? I tried to make db connection a static class so that I can use globally in any class without having to use $this->pdo.

The error shown is:

Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\carRental\index.php on line 44

<?php
class connection
{
    public static $servername = "localhost";
    public static $username = "root";
    public static $password = "";
    public static $dbname = "carrental";
    public static $port="3306";
    public static $pdo;

    public static function addConnection()
    {
      try {
          self::$pdo = new PDO("mysql:host=self::$servername;port=self::$port;dbname=self::$dbname", self::$username, self::$password);
          self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      } catch(PDOException $e) {
          echo 'ERROR: ' . $e->getMessage();
      }

      self::$pdo->query("use self::$dbname");
      return self::$pdo;
    }
}
class car 
{
    public $name;
    public $maker;
    public $type;
    public $colour;
    public $passanger;

    public function __construct($param1,$param2,$param3,$param4,$param5)
    {
        $this->name=$param1;
        $this->maker=$param2;
        $this->type=$param3;
        $this->colour=$param4;
        $this->passanger=$param5;

    }
    public function addCar()
    {
        $sql="INSERT INTO car(car_name,car_maker,car_type,car_colour,num_passanger)VALUES('{$this->name}','{$this->maker}', '{$this->type}','{$this->colour}','{$this->passanger}')";
        $stmt =connection::$pdo->prepare($sql);
        $stmt->execute();
        echo "Data inserted!";
    }
}

$car1=new car("Honda Accord","Honda","5 wheeler","Red",9);
$car1->addCar();

?>
3
  • 4
    You never called: addConnection() Commented Jul 7, 2015 at 14:33
  • @Rizier123 Ahhh gold, I was looking for the typo or trying to spot the error in empty vars :) Commented Jul 7, 2015 at 14:35
  • 1
    maybe you will want to call addConnection() method into the car constructor method to avoid have to call it in a every method into the car class. Commented Jul 7, 2015 at 14:46

1 Answer 1

1

As @Rizier123 already said in the comment, you didn't call addConnection(). So, you might need to do this, inside the addCar() method of class car

$sql="INSERT INTO car(car_name,car_maker,car_type,car_colour,num_passanger)VALUES('{$this->name}','{$this->maker}', '{$this->type}','{$this->colour}','{$this->passanger}')";

$pdo_obj = connection::addConnection(); //get the pdo object
$stmt = $pdo_obj->prepare($sql);
$stmt->execute();
echo "Data inserted!";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.