-1

I connect to database then use class , I can't use database there .. I use namespaces .. I'm a beginner and I don't know much about it.

I tried to search for a solution, but I couldn't find anything can help. Please guide me to any tutorial if it will help .

server.php

//Connect to database
$host = 'localhost';
$db   = 'market';
$user = 'root';
$pass = '';
$dsn = 'mysql:host=localhost;dbname=market';
try {
    $pdo = new \PDO($dsn, $user, $pass);
    // set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}
catch(\PDOException $e)
{
    echo "Connection failed: " . $e->getMessage();
}

index.php

require 'server.php';
require 'vendor/autoload.php';
use App\Product;
$product= new Product;
$product->all();

product.php

namespace App;
Class Product
{
protected $rate;
protected $name;
protected $cost;
public function all()
{
    $sql = 'SELECT product,price,rating FROM products';
    $q = $pdo->query($sql);
}

I expect it to know what is $pdo as I require server.php in index.php But it throws :"Fatal error: Uncaught Error: Call to a member function query() on null in Market\src\Product.php:14 please guide me how to connect to database in my classes ..

A J
  • 1,439
  • 4
  • 25
  • 42

2 Answers2

0

move your require 'server.php'; in the all () function of the Product class and this should work like this:

namespace App;
Class Product
{
    protected $rate;
    protected $name;
    protected $cost;
    public function all()
    {
        require_once ('server.php');
        $sql = 'SELECT product,price,rating FROM products';
        $q = $pdo->query($sql);
    }
}
0

From a quick look since the lack of the global keyword could be your issue when using the pdo object

try global $pdo; at the top of your all() function

Marky Ross
  • 41
  • 5