在PHP中设置数据库连接类

在PHP中设置数据库连接类,php,mysql,database,Php,Mysql,Database,最近有人向我介绍了PHP中类的概念,经过一些研究,我得出结论,我需要在类中存储与数据库相关的函数,以便以后访问。它在大部分情况下都是有效的,但是我仍然对一些用例感到困惑。比如说, 下面是我通常如何连接到数据库并在表中显示来自用户id的信息的示例 dbcon.php: <?php $con = mysqli_connect("host","username","password","database") or die("Couldn't connect"); require_once("f

最近有人向我介绍了PHP中类的概念,经过一些研究,我得出结论,我需要在类中存储与数据库相关的函数,以便以后访问。它在大部分情况下都是有效的,但是我仍然对一些用例感到困惑。比如说,

下面是我通常如何连接到数据库并在表中显示来自用户id的信息的示例

dbcon.php:

<?php
$con = mysqli_connect("host","username","password","database") or die("Couldn't connect");

require_once("functions.php");
?>
require_once("dbcon.php");

$result = mysqli_query($con, "SELECT * FROM tablename");
while ($row = mysqli_fetch_assoc($result)) {
    $userinfo = getUserInfo($row['userid']);
    echo $userinfo['name'];
}

?>
一些随机文件:

<?php
$con = mysqli_connect("host","username","password","database") or die("Couldn't connect");

require_once("functions.php");
?>
require_once("dbcon.php");

$result = mysqli_query($con, "SELECT * FROM tablename");
while ($row = mysqli_fetch_assoc($result)) {
    $userinfo = getUserInfo($row['userid']);
    echo $userinfo['name'];
}

?>
我不认为这种查询数据库和显示信息的方法是可能的最整洁或最有效的方法。我读了一篇关于使用类篡改数据库并调用我在类中创建的函数的文章

我的第一个问题是:当我试图访问functions.php中的$con时,它是未定义的。如何通过require_once函数将变量从dbcon.php传递到functions.php

我还想知道存储数据库连接的最佳方式是什么,是否有关于如何设置的教程


我希望你能理解lol.

你可以这样做:-

Dbconnection.php:-

<?php
Class DbConnection{
    function getdbconnect(){
        $conn = mysqli_connect("host","username","password","database") or die("Couldn't connect");
        return $conn;
    }
}
?>
<?php
require_once('Dbconnection.php');
Class WorkingExamples{
    function getUserInfo($id) {
        $Dbobj = new DbConnection(); 
        $query = mysqli_query($Dbobj->getdbconnect(), "SELECT * FROM users WHERE id = '$id'");
        return mysqli_fetch_array($query);
    }
}
$data = new WorkingExamples();
echo "<pre/>";print_r($data->getUserInfo(3));
?>


实际上已经有了这样一个类:)@developerAren Well-dang。您每天都会学到一些新的东西:DIf您创建一个类来管理您的连接,并使用require_once命令添加该类文件。您只需要实例化类
$myDBclass=new DBClass()
,然后使用类中的con变量,类似于
$myDBclass->con
将数据库连接用户名和密码设置为常量是非常糟糕的做法。这使得PHP应用程序全局可用,这是一个重要的安全问题。您的连接值只使用一次,并且只在脚本后面几行使用,因此只需将它们设置为私有变量即可。一旦连接成功,
unset
就会取消连接。这只是一个例子@Martin,但谢谢你的建议。很高兴听到你这么说。
 <?php
class Database{
   const DB_HOSTNAME = 'localhost';
   const DB_USERNAME = 'root';
   const DB_PASSWORD = 'root';
   const DB_NAME = 'stockganesha';
   public $_db_connect;
   protected $_sql;
   protected $_result;
   protected $_row;

   function db_connect(){
     $this->_db_connect = mysqli_connect(self::DB_HOSTNAME,self::DB_USERNAME,self::DB_PASSWORD,self::DB_NAME) or die(mysql_error());
     return $this->_db_connect;
   }

   function sql(){
       $this->_sql = 'SELECT * FROM customers';
   }

   function query(){
       $this->_result = mysqli_query($this->_db_connect,$this->_sql);
   }

   function fetch_array(){
       while($this->_row = mysqli_fetch_array($this->_result)){
           $username = $this->_row['first_name'];

           echo "<ul>";
               echo "<li>".$username."</li>";
           echo "</ul>";
       }
   }

   function db_close(){
       mysqli_close($this->_db_connect);
   }
}
<?php

require_once('../Config/Dbconnection.php');
include './model.php';

class CustomerDTO{

    private $mysql;
    function __construct() {
        $database = new Database();
        $this->mysql  = $database->db_connect(); 
    }
    function create($customer){
        $firstName = $customer->getFirstName();
        $lastName = $customer->getLastName();
        $emailId = $customer->getEmailId();
        $mobileNumber = $customer->getMobileNumber();
        $dateOfBirth = $customer->getDateOfBirth();
        $phoneNumber = $customer->getPhoneNumber();
        $termAndCondtion = $customer->getTermAndCondition(); 

       $result =  mysqli_query($this->mysql, "Insert into customers (first_name,last_name,email_id,mobile_number,date_of_birth,phone_number,term_and_condition)
       values('$firstName','$lastName','$emailId','$mobileNumber','$dateOfBirth','$phoneNumber','$termAndCondtion')");
        
       return $result;
    }

    function read(){
        $result = mysqli_query( $this->mysql, "Select * from customers");
        return $result;
    }

    function update($id, $customer){
        $result = mysqli_query($this->mysql, "update customers set 
            first_name = ".$customer->getFirstName()."
            last_name = ".$customer->getLastName()."
            email_id = ".$customer->getEmailId()."
            mobile_number = ".$customer->getMobileNumber()."
            date_of_birth = ".$customer->getDateOfBirth()."
            phone_number = ".$customer->getPhoneNumber()."
            term_and_condition = ".$customer->getTermAndCondition()."
            where id = ".$customer->getId());
        
        return $result;
    }

    public function delete($id){
      $result = mysqli_query($this->mysql, "delete from customers where id =".$id);
      return $result;
    }
}