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