gpt4 book ai didi

php - 将mysql数据库转为php中的pdo类

转载 作者:行者123 更新时间:2023-11-29 12:43:29 26 4
gpt4 key购买 nike

我有一个数据表,我想创建 pdo 类来对其进行操作,并将数据表的字段转换为我可以访问它们的公共(public)变量。

示例:

<?php 
class personne
{
//code to get fields from datatable and turn them to variables
}

$p=personne::find(1); //find personne who have 1 as id
echo $p->nom;
?>

以及变量值中存储的字段的值

谢谢。

最佳答案

这里是:

class Person {

private static $instance = null;
private $db;
private static $data;

private function __construct() {
try {
$pdo_param = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$this->db = new PDO("mysql:host=YOUR_HOST_NAME;dbname=YOUR_DB_NAME", "YOUR_USERNAME", "YOUR_PASSWORD", $pdo_param);
}
catch(PDOException $e) {
die($e->getMessage());
}
}

private static function getInstance() {
if (self::$instance == null) {
self::$instance = new self();
}
return self::$instance;
}

public static function find($id) {
try {
$instance = self::getInstance();
$result = $instance->db->query(YOUR_SQL_QUERY);
self::$data = (object)$result->fetch();
return self::$data;
}
catch(PDOException $e) {
die($e->getMessage());
}
}

}

$p = Person::find(1);
echo $p->name;

关于php - 将mysql数据库转为php中的pdo类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25784181/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com