我对PDO的执行命令是有原因的吗?

发布于 2025-02-04 10:41:45 字数 1583 浏览 4 评论 0原文

我刚刚开始通过YouTube上的视频了解php OOP,我正在关注构建网站应用程序。

正如那个人所解释的那样,我必须使用PDO连接到SQL数据库。我遵循了他所做的一切,但是我的PDO执行部分不起作用,我不知道这是什么问题。代码在下面。它不会带来任何错误,只是没有带回数据库中的任何数据。我在函数之间放了一些回声,以找出代码走的距离,这就是我发现它准备查询但从未执行的。请帮助我解决这个问题。谢谢。

class Database{
private function connect()
{
    $string = DBDRIVER . ":host =" .DBHOST.";dbname =".DBNAME;
    if ($conn = new PDO($string, DBUSER, DBPASS)) {
        return $conn;
    } else {
        die("Could not connect to database");
    }
}

上面的代码是与数据库的连接。据我所知,它正常工作。

下面的代码应该将数据库中的数据返回以使用view.php文件显示的数据库返回

public function query($query, $data = array(), $data_type = "object")
{

    $con = $this->connect();
    $stm = $con->prepare($query);
    print_r($stm);

    if ($stm) {
        $check = $stm->execute($data); //right here is where I concluded that the code stops
        print_r($check);//does not print anything
        if ($check) {
            if ($data_type == "object") {
                $data = $stm->fetchAll(PDO::FETCH_OBJ);
            } else {
                $data = $stm->fetchAll(PDO::FETCH_ASSOC);
            }

            if (is_array($data) && count($data) > 0) {
                return $data;
            }
        }
    }
    return false;
}

,这是控制器中编写的零件,将查询分配给数据库以执行。

function index(){

        $db = new Database();
        
        $data = $db->query("select * from users");
        if($data){echo $data;} //echos nothing because $data is empty
        $this -> view('home', ['rows' => $data]);
    }

I am just beginning to learn about PHP OOP through videos on youtube and I am following along in building a website application.

I have to connect to the SQL database using PDO as the guy explained. I followed everything he did but my execution part for the PDO is not working and I don't know what is wrong with it. The code is below. it does not bring up any errors it just doesn't bring back any data from the database. I put some echos in between the function to find out how far the code is going and that is how I found out that it prepares the query but never executes it. Please help me figure this out. Thank you.

class Database{
private function connect()
{
    $string = DBDRIVER . ":host =" .DBHOST.";dbname =".DBNAME;
    if ($conn = new PDO($string, DBUSER, DBPASS)) {
        return $conn;
    } else {
        die("Could not connect to database");
    }
}

The code above is the connection to the database. it is working correctly as far as I can tell.

The code below is supposed to return the data from the database back to be displayed using a view.php file

public function query($query, $data = array(), $data_type = "object")
{

    $con = $this->connect();
    $stm = $con->prepare($query);
    print_r($stm);

    if ($stm) {
        $check = $stm->execute($data); //right here is where I concluded that the code stops
        print_r($check);//does not print anything
        if ($check) {
            if ($data_type == "object") {
                $data = $stm->fetchAll(PDO::FETCH_OBJ);
            } else {
                $data = $stm->fetchAll(PDO::FETCH_ASSOC);
            }

            if (is_array($data) && count($data) > 0) {
                return $data;
            }
        }
    }
    return false;
}

below is the part written in the controller to assign the query to the database to execute.

function index(){

        $db = new Database();
        
        $data = $db->query("select * from users");
        if($data){echo $data;} //echos nothing because $data is empty
        $this -> view('home', ['rows' => $data]);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

煮酒 2025-02-11 10:41:45

我已经测试了您的代码,因此发生了错误,因为您在dbname和=之间有一个空间。 DBNAME之后的半隆(不需要)。

class Database{
private function connect()
{
    $string = DBDRIVER . ":host=" .DBHOST.";dbname=".DBNAME.";";
    if ($conn = new PDO($string, DBUSER, DBPASS)) {
        return $conn;
    } else {
        die("Could not connect to database");
    }
}

现在对我有用。

我很长一段时间以来使用此连接类,也许您想使用它。

class Connection{

    private const CONNECTION = [
        "Host" => "",
        "User" => "",
        "Password" => "",
        "Databasename" => ""
    ];

    /**
     * Includes the pdo connection.
     * @var \PDO|null
     */
    private \PDO|null $PDO = null;

    /**
     * Includes the already called instance.
     * @var Connection|null
     */
    private static self|null $Connection = null;

    /**
     * Creates the DB connection and sets it to the class.
     * @return void 
     * @throws Exception 
     */
    private function __construct()
    {
        $Connection_str = 'mysql:';
        $Connection_str .= 'host=' . self::CONNECTION["Host"] . ';';
        $Connection_str .= 'dbname=' . self::CONNECTION["Databasename"] . ';';
        $Connection_str .= 'charset=utf8mb4';
        $this->PDO = new \PDO($Connection_str, self::CONNECTION["User"], self::CONNECTION["Password"]);
        $this->PDO->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->PDO->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        $this->PDO->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
    }

    /**
     * Returns the static DB connection instance.
     * @return Connection 
     * @throws Exception 
     */
    public static function get(): Connection
    {
        return !isset(self::$Connection) ? self::$Connection = new self : self::$Connection;
    }

    /**
     * Returns the PDO instance.
     * @return PDO 
     * @throws Exception 
     */
    public function getPDO(): \PDO
    {
        return $this->PDO;
    }
}

您可以使用以下代码使用连接类:

$SQLString = "select * from users";
$Data = [

];
$Query = Connection::get()->getPDO()->prepare($SQLString);
$Query->execute($Data);
$Data = $Query->fetchAll();

i have tested your code the error occurs because u have a space between the dbname and the =. A semicolon after the DBNAME is also missing (it is not needed).

class Database{
private function connect()
{
    $string = DBDRIVER . ":host=" .DBHOST.";dbname=".DBNAME.";";
    if ($conn = new PDO($string, DBUSER, DBPASS)) {
        return $conn;
    } else {
        die("Could not connect to database");
    }
}

Now it works for me.

i am using this connection class for a long time, maybe you want to use it.

class Connection{

    private const CONNECTION = [
        "Host" => "",
        "User" => "",
        "Password" => "",
        "Databasename" => ""
    ];

    /**
     * Includes the pdo connection.
     * @var \PDO|null
     */
    private \PDO|null $PDO = null;

    /**
     * Includes the already called instance.
     * @var Connection|null
     */
    private static self|null $Connection = null;

    /**
     * Creates the DB connection and sets it to the class.
     * @return void 
     * @throws Exception 
     */
    private function __construct()
    {
        $Connection_str = 'mysql:';
        $Connection_str .= 'host=' . self::CONNECTION["Host"] . ';';
        $Connection_str .= 'dbname=' . self::CONNECTION["Databasename"] . ';';
        $Connection_str .= 'charset=utf8mb4';
        $this->PDO = new \PDO($Connection_str, self::CONNECTION["User"], self::CONNECTION["Password"]);
        $this->PDO->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->PDO->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        $this->PDO->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
    }

    /**
     * Returns the static DB connection instance.
     * @return Connection 
     * @throws Exception 
     */
    public static function get(): Connection
    {
        return !isset(self::$Connection) ? self::$Connection = new self : self::$Connection;
    }

    /**
     * Returns the PDO instance.
     * @return PDO 
     * @throws Exception 
     */
    public function getPDO(): \PDO
    {
        return $this->PDO;
    }
}

You can use the connection class using the following code:

$SQLString = "select * from users";
$Data = [

];
$Query = Connection::get()->getPDO()->prepare($SQLString);
$Query->execute($Data);
$Data = $Query->fetchAll();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文