PHP - PDO“配置”文件等效项
这可能是一个以前已经回答过的问题 - 如果是这样,请在下面发表评论,我将删除这个问题。
我一直在学习 PHP 课程,同时转向 PDO。
我似乎找不到的一个概念是如何用类来完成与此等效的操作:
config.php
<?php
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$con = mysql_connect($host, $user, $pass) or die("MySQL Error");
mysql_select_db("account_db", $con);
?>
another.php
<?php
require_once('config.php');
$selectStatement = "SELET foo FROM bar";
$selectQuery = mysql_query($selectStatement, $con);
?>
我还没有完全弄清楚如何为 PDO 连接创建配置文件/类,然后在另一个类中使用它,即用户如下:
<?php
class Users
{
private $_userId;
function setUserId($username)
{
// Use a predefined database handle to connect to a database to get the users ID - I assume using a preconfigured $dbh handle via an include or extend?
$sth = $dbh->prepare("SELECT id FROM users WHERE username = :username");
$sth->bindParam(':username', $username);
...
}
}
?>
谢谢大家:)
This may be a question that has been answered before - if so please just leave a comment below and I'll remove this one.
I have been learning classes in PHP and at the same time making the jump to PDO.
One concept I cant seem to find is how to acomplish the equivalent to this with classes:
config.php
<?php
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$con = mysql_connect($host, $user, $pass) or die("MySQL Error");
mysql_select_db("account_db", $con);
?>
another.php
<?php
require_once('config.php');
$selectStatement = "SELET foo FROM bar";
$selectQuery = mysql_query($selectStatement, $con);
?>
I haven't quite figured out how I would create a config file/class for a PDO connection and then use it in another class, i.e. Users as below:
<?php
class Users
{
private $_userId;
function setUserId($username)
{
// Use a predefined database handle to connect to a database to get the users ID - I assume using a preconfigured $dbh handle via an include or extend?
$sth = $dbh->prepare("SELECT id FROM users WHERE username = :username");
$sth->bindParam(':username', $username);
...
}
}
?>
Thanks all :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我的项目中,我更喜欢使用带有静态成员的类来保存 PDO 对象。
我可以像这样访问它:
In my projects, I prefer using a class with a static member which holds the PDO object.
The I can access it like so: