所以我不知道在哪里您取得$id
我跑这一关获取的所有数据。
我通常会将我的代码分解为文件和文件夹,因为我发现这更容易与其他人合作。
// database connection file (dbc.php)
class Database
{
private $host = "127.0.0.1";
private $db = "";
private $user = "";
private $password = "";
public $conn;
public function dbConnect()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db, $this->user, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
我然后做一个普通的文件,在这里,您可以存储所有常用的功能或你的静态功能
// Common file (common.php)
require_once('dbc.php');
class DBCommon
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnect();
$this->conn = $db;
}
public function run($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
所以要更多地解释这一点,你会看到一个功能的run()
这仅仅是节省了繁琐的$this->conn->prepare
每个查询。现在你可以运行$this->run()
下一个会是你的类文件..这是你的逻辑是:
// your class file... (class.btc.php)
require_once "common.php";
class BTC extends DBCommon
{
public function getQuery()
{
$stmt = $this->run("SELECT * FROM `btc`");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_OBJ))
{
$rows[] = $row;
}
return $rows;
}
}
自我解释..
然后你调用方法..比方说index.php
// File you're calling your class from (index.php)
require_once "class.btc.php";
$fetch = new BTC();
$returnData = $fetch->getQuery();
foreach ($returnData as $data)
{
echo
"<p>$data->something</p>
<p>$data->somethingElse</p>";
}
这似乎有点长篇大论,我知道,但时间你会整体保存会帮助!
您可以发布您从 – Option
调用此类的另一个文件吗您在您的语句中也容易受到SQL注入的影响 – Option
您准备做什么?您的类扩展了PDO,但尝试使用另一个PDO实例。你想做什么? –