我是PHP编程的初学者,我想要一个小问题的帮助。请看下面的代码:
PHP代码
<?php
class Account
{
public function register()
{
$db_link = mysql_connect("localhost","root",""); // Create Connection
if (!$db_link) // Check connection
{
die(mysql_error());
}
mysql_close($db_link); // Close Connection
}
public function login()
{
$con = mysql_connect("localhost","root","") // create connection
if (!$con) // create connection
{
die(mysql_error());
}
mysql_close($con); //close connection
}
}
?>我的问题是,是否为每个对象的方法创建单独的db链接是最好的方法?是否有更好的或替代的方法来做到这一点?希望我已经解释得够好了。
以下内容是否正确?
$x = new Account("localhost", "root", "");-and x会有自己的connection...and,然后当它完成时关闭?
发布于 2012-01-02 23:22:58
我不建议以这种方式创建数据库连接。创建一个连接并使用它将其注入对象。您不需要为每个对象创建一个新的连接。
代码示例:
$connection = new mysqli('localhost', 'user', 'password');
$Account = new Account($connection);需要将Account更改为:
class Account {
protected $connection;
public function __construct(mysqli $connection) {
$this->connection = $connection;
}
public function register() {
// use $this->connection for db
}
public function login() {
// use $this->connection for db
}
}我还建议您看看关于选择php.net API的MySQL文档。如果您真的想在PHP和MySQL中使用OOP,您将需要切换到mysqli或PDO,因为您使用的API并不真正支持OOP接口。
发布于 2012-01-02 23:33:17
我建议:
public function __construct(mysqli $connection) {
$this->connection = $connection;
if(!$this->$connection) {
die(mysql_error());
}
}
public function __destruct() {
mysql_close($this->$connection);
}发布于 2012-01-02 23:31:06
您可以使用如下代码:
$db_link = mysql_connect("localhost","root",""); // Create Connection
if (!$db_link) // Check connection
{
die(mysql_error());
}
mysql_select_db("db_name");
$q=mysql_query("SELECET * FROM table_name LIMIT 1");其他查询将出现在这里
mysql_close($db_link); // Close Connection在每个页面上创建一个连接就足够了。多个连接或断开与sql服务器的连接和再次丢失可能会导致性能下降。
https://stackoverflow.com/questions/8706317
复制相似问题