创建一个PHP PDO数据库类,OOP麻烦 [英] Creating a PHP PDO database class, trouble with the OOP

查看:57
本文介绍了创建一个PHP PDO数据库类,OOP麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我当前的数据库类:

this is my current Database class:

class Database {

    private $db;

    function Connect() {
        $db_host = "localhost";
        $db_name = "database1";
        $db_user = "root";
        $db_pass = "root";
        try {
            $this->db = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user, $db_pass);
        } catch(PDOException $e) {
            die($e);
        }
    }

    public function getColumn($tableName, $unknownColumnName, $columnOneName, $columnOneValue, $columnTwoName = "1", $columnTwoValue = "1") {
        $stmt = $this->db->query("SELECT $tableName FROM $unknownColumnName WHERE $columnOneName='$columnOneValue' AND $columnTwoName='$columnTwoValue'");
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $results[0][$unknownColumnName];
    }
}

我正在尝试使用以下代码运行它:

I'm trying to run it using the following code:

$db = new Database();
$db->Connect();
echo $db->getColumn("Sessions", "token", "uid", 1);

我得到以下错误:

PHP致命错误:在第19行的/Users/RETRACTED/RETRACTED/root/includes/Database.php中的非对象上调用成员函数fetchAll()

PHP Fatal error: Call to a member function fetchAll() on a non-object in /Users/RETRACTED/RETRACTED/root/includes/Database.php on line 19

有什么想法吗?谢谢

推荐答案

  1. 此功能易于进行SQL注入.
  2. 此功能不允许您使用最简单的OR条件获取列.
  3. 此功能使SQL语言几乎是自然的英语变得乱码.
  1. This function is prone to SQL injection.
  2. This function won't let you get a column using even simplest OR condition.
  3. This function makes unreadable gibberish out of almost natural English of SQL language.

看,您甚至宠爱了自己编写此功能.您如何将其用于日常编码?实际上,与使用原始PDO相比,此功能使您的体验更难-您必须学习所有新语法,大量异常和最新修正.

Look, you even spoiled yourself writing this very function. How do you suppose it to be used for the every day coding? As a matter of fact, this function makes your experience harder than with raw PDO - you have to learn all the new syntax, numerous exceptions and last-minute corrections.

请回到原始PDO!

让我告诉你正确的方法

public function getColumn($sql, $params)
{
    $stmt = $this->db->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchColumn();
}

像这样使用

echo $db->getColumn("SELECT token FROM Sessions WHERE uid = ?", array(1));

这样,您将能够使用 SQL的全部功能,不仅限于愚蠢的子集,而且还具有准备好的语句的安全性,同时还能保留代码可理解的.
仍然一行通话-这是您最初的意图(也是非常正确的!).

This way you'll be able to use the full power of SQL not limited to a silly subset, as well as security of prepared statements, yet keep your code comprehensible.
While calling it still in one line - which was your initial (and extremely proper!) intention.

这篇关于创建一个PHP PDO数据库类,OOP麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆