所以这里有一个基本示例可以帮助您开始使用 PHP。如果您需要从数据库中获取查询,这是最合适的选择。
首先,将文件扩展名更改为 .php 而不是 .html
然后:
创建你的数据库连接文件:
/**
* database.php
*/
class Database
{
private $host = "localhost";
private $db_name = "dbname";
private $username = "username";
private $password = "password";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
然后我建议制作一个 dbCommon.php 文件:
/**
* dbCommon.php
*/
require_once ('database.php');
class DBCommon
{
private $conn;
/** @var Common */
public $common;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
您可以从引导程序中添加一些东西,例如:
public function error($message)
{
$this->messages[] = '<div class="alert alert-danger">' . $message . '</div>';
}
在 dbCommon.php 文件中。
完成这些后,您需要为自己创建一个类文件以添加您的逻辑。以下是您的代码外观的基本示例:
/**
* class.queries.php
*/
require_once ('dbCommon.php');
class queries extends DBCommon
{
public function __construct()
{
parent:: __construct();
}
public function sales()
{
$stmt = $this->runQuery("SELECT * FROM `sales_flat_order`");
$stmt->execute();
$res = $stmt->fetch(PDO::FETCH_OBJ);
return $res;
}
}
最后,在此之后您需要返回到 file.php(最初是 .html)并将其添加到顶部:
<?php
require_once ('class.queries.php');
$fetch = new queries();
$info = $fetch->sales();
?>
这意味着您现在可以按照自己的选择和方式获取信息,您只需回显$info->columnName
我并不是要为您擦鼻子,但希望这将为您提供进入 PDO 和正确执行 PHP 查询的指导。