我有一个关于如何绘制连接到函数内部的选择框的问题。
我这样说:
功能MySQL: mysql.php
function conectar() {
try {
$dbh = new PDO("mysql:host=localhost;dbname=adm-new", 'root', '');
} catch (PDOException $dbe) {
echo $dbe->getMessage();
}
return $dbh;
}
$conn = conectar();
功能选择: menu.php
function z_menu_todos() {
global $conn;
$z_menu = "SELECT *
FROM z_menu
ORDER BY posicao ASC";
return $conn->prepare($z_menu);
}
我不想调用变量global $ conn。 什么是最好的方法?
答案 0 :(得分:0)
我会创建一个DatabaseFactory
类,用于创建数据库连接,如下所示:
<强> ConnectionFactory.php 强>
class ConnectionFactory {
private $_connection;
public function __construct($dbName, $dbUser, $dbPassword, $dbHost = 'localhost'){
try {
$this->_connection = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPassword);
$this->_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
throw new DatabaseFactoryException('Could not create connection:' . $e->getMessage());
}
}
public function getConnection(){
return $this->_connection;
}
}
之后我会创建MenuRepository
类,用于执行与Menu关联的查询,如下所示:
<强> MenuRepository.php 强>
class MenuRepository {
private $_connection;
public function __construct(PDO $connection){
$this->_connection = $connection;
}
public function getMenus(){
$stmt = $this->_connection->prepare("SELECT * FROM z_menu ORDER BY posicao ASC");
$stmt->execute();
return $stmt->fetchAll();
}
}
我会在单独的文件中创建配置,如下所示:
<强>的config.php 强>
define('DB_NAME', 'adm-new');
define('DB_USER', 'root');
define('DB_PASS', '');
之后我会使用:
<强>的index.php 强>
require __DIR__ . '/config.php';
require __DIR__ . '/ConnectionFactory.php';
require __DIR__ . '/MenuRepository.php';
$connectionFactory = new ConnectionFactory(DB_NAME, DB_USER, DB_PASS);
$connection = $connectionFactory->getConnection();
$menuRepository = new MenuRepository($connection);
$menus = $menuRepository->getMenus();
答案 1 :(得分:-1)
class Database
{
protected $conn;
public function __construct()
{
try {
$this->conn = new PDO("mysql:host=localhost;dbname=adm-new", 'root', '');
} catch (PDOException $dbe) {
echo $this->conn->getMessage();
}
}
public function z_menu_todos()
{
$z_menu = "SELECT *
FROM z_menu
ORDER BY posicao ASC";
return $this->conn->prepare($z_menu);
}
}
<强>用法强>
$database = new Database();
$stmt = $database->z_menu_todos();
根据需要修改此项,这是如何执行此操作的一个非常基本的示例,不要只是复制并粘贴它。
答案 2 :(得分:-1)
在这种情况下,您应该避免使用全局变量,因为您可以轻松地将连接作为方法参数传递给方法,如下所示:
function conectar() {
try {
$dbh = new PDO("mysql:host=localhost;dbname=adm-new", 'root', '');
} catch (PDOException $dbe) {
echo $dbe->getMessage();
}
return $dbh;
}
$conn = conectar();
function z_menu_todos($conn) {
$z_menu = "SELECT * FROM z_menu ORDER BY posicao ASC";
return $conn->prepare($z_menu);
}
但是,创建一个单独的类来管理数据库连接和其他纯粹与数据库相关的东西以及另一个用于对菜单表执行SQL查询的类可能是个好主意。