[英]Creating a PHP PDO database class, trouble with the 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);
And i get the following error: 我收到以下错误:
PHP Fatal error: Call to a member function fetchAll() on a non-object in /Users/RETRACTED/RETRACTED/root/includes/Database.php on line 19 PHP致命错误:在第19行的/Users/RETRACTED/RETRACTED/root/includes/Database.php中的非对象上调用成员函数fetchAll()
Any idea what's up? 知道怎么了? Thanks 谢谢
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 更难 - 您必须学习所有新语法,众多例外和最后修正。
Please, turn back to raw PDO! 请转回原始PDO!
Let me show you the right way 让我告诉你正确的方法
public function getColumn($sql, $params)
{
$stmt = $this->db->prepare($sql);
$stmt->execute($params);
return $stmt->fetchColumn();
}
used like this 像这样用过
echo $db->getColumn("SELECT token FROM Sessions WHERE uid = ?", array(1));
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. 通过这种方式,您将能够充分利用SQL的全部功能,不仅限于愚蠢的子集,还可以使用预处理语句的安全性 ,同时保持代码易于理解。
While calling it still in one line - which was your initial (and extremely proper!) intention. 虽然称它仍在一行 - 这是你的初始(并且非常合适!)意图。
it means your $stmt variable is not returning a PDOStatement object. 这意味着你的$ stmt变量没有返回PDOStatement对象。 your query is failing since PDO::query either returns a PDOStatement or False on error. 您的查询失败,因为PDO :: query要么返回PDOStatement,要么在出错时返回False。
Use fetch
instead of fetchAll
..that will be easy in your case 使用fetch
而不是fetchAll
..在你的情况下很容易
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results[0][$unknownColumnName];
It will be 这将是
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results[$unknownColumnName];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.