【发布时间】:2019-09-15 10:42:25
【问题描述】:
我连接到数据库然后使用类,我不能在那里使用数据库.. 我使用命名空间..我是初学者,对此了解不多。
我试图寻找解决方案,但找不到任何帮助。如果有帮助,请指导我学习任何教程。
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);
}
我希望它知道 $pdo 是什么,因为我需要 index.php 中的 server.php
但它抛出:“致命错误:Uncaught Error: Call to a member function query() on null in Market\src\Product.php:14
请指导我如何在我的课程中连接到数据库..
【问题讨论】:
标签: php pdo namespaces