PHP OOP MySQL编程 [英] PHP OOP MySQL Programming

查看:48
本文介绍了PHP OOP MySQL编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP编程的初学者,希望获得一个小问题的帮助.请看下面的代码:

I am a beginner in PHP programming and would like help with a little question. Please take a look at the code below:

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
  }

}
?>


我的问题是,为对象的每个方法创建单独的数据库链接是否是最好的方法?有更好的方法或替代方法吗?希望我已经讲得足够好了.


My question is if creating individual db links for every single one of the object's methods is the best way to go? Is there a better or alternative way to do this? Hopefully I've explained well enough.

以下内容正确吗?

$x = new Account("localhost", "root", "");

-和x将有自己的连接...然后在完成后关闭?

-and x would have its own connection...and then close when its done?

推荐答案

我不建议以此方式创建数据库连接.创建一个连接,并使用该连接将其注入到对象中.您不需要为每个对象创建一个新的连接.

I would not advise creating your database connections this way. Create one connection and inject that into the object using it. You should not need to create a new connection for every object.

代码示例:

$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有关选择MySQL API的文档.如果您确实想将OOP与PHP和MySQL一起使用,则需要切换到mysqliPDO,因为您使用的API并不真正支持OOP接口.


I would also suggest that you take a look at the php.net docs about choosing a MySQL API. If you really want to use OOP with PHP and MySQL you will need to swap over to mysqli or PDO as the API you are using does not truly support an OOP interface.

这篇关于PHP OOP MySQL编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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