【问题标题】:How Do I read the Database?如何读取数据库?
【发布时间】:2021-08-25 15:36:21
【问题描述】:

这是core下的config.php文件

<?php

define("WEBSITE_TITLE", 'MY SHOP');

//database details
define('DB_NAME', "eshop_db");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_TYPE', "mysql");
define('DB_HOST', "localhost");


define('THEME','eshop/');
define('DEBUG', true);
if(DEBUG){
    ini_set('display_errors', 1);
}else{
    ini_set('display_errors', 0);
}
?>

这里我将我的数据库名称定义为 eshop_db 和其余数据

这是我的core文件夹下的database.php文件

<?php 

Class Database{
    public static $con;
    public function __construct()
    {
        try{
 
            $string = DB_TYPE . ":host=".DB_HOST . ";dbname=" . DB_NAME;
            self::$con = new PDO($string,DB_USER,DB_PASS);

        }catch (PDOException $e){

             die($e->getMessage());
        }
    }

    public static function getInstence(){
        if(self::$con){
            return self::$con;
        }
        return $instance = new self();
        // return self::$con;
    }

        //read function 
    public function read($query,$data = array()){
        $stm = self::$con->prepare($query);
        $result = $stm->execute();
        if($result){
            $data = $stm->fetchAll(PDO::FETCH_OBJ);
            if(is_array($data)){

                return $data;

            }
        }
            return false;
    }


    public function write($query,$data = array()){

    }
   
}

$db = Database::getInstence();
$data = $db->read("discribe users");
show($data);

在我的数据库文件中,我首先创建了一个类并创建了数据库连接,还检查了数据库连接。连接似乎正常,但是当我尝试读取数据库中的“用户”表时,它没有显示任何内容,文件中也没有错误。

这是我第一次使用 PDO。我正在使用 xampp。在使用 PDO 之前我需要安装任何东西吗?你能帮我解决这个问题吗?

【问题讨论】:

  • 我假设 $data 为假,因为您的 SQL 查询无效(“描述”,而不是“描述”)。
  • @NevilleKuyt 哦,多么愚蠢的错误,非常感谢。更正描述它现在的工作。
  • 请注意:您使用的是 MVC。因此,与其在类、函数等中使用大量 try-catch 块,不如在应用程序的入口点只使用一个 try-catch 块(可能index.php)。像这样:try{ /* ...Create and use class instances of your app... */ } catch (\Throwable $throwable) { /* ...Present the _Error_ or _Exception_ object thrown either automatically by the system, or by you, the developer, via a _throw_ statement, to the user... */ }.
  • 或者(推荐)您可以定义错误处理函数,供set_error_handlerset_exception_handlerregister_shutdown_function 使用。有关基于 MVC 的应用程序中的错误处理的更多详细信息,我强烈建议您阅读this tutorial。关于 PDO,我也强烈推荐你 this tutorial

标签: php mysql model-view-controller


【解决方案1】:
$db = Database::getInstence();
$data = $db->read("describe users");
show($data);

感谢@NevilleKuy,它必须是“描述”,以前是“描述”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多