在PHP中设置数据库连接类

时间:2016-01-24 04:18:08

标签: php mysql database

最近我介绍了PHP中的类的概念,经过一些研究后我得出结论,我需要在类中存储数据库相关的函数以便以后访问。它在很大程度上起作用,但是我仍然困惑的一些用例。例如,

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

dbcon.php:

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

require_once("functions.php");
?>

的functions.php

function getUserInfo($id) {
    $query = mysqli_query($con, "SELECT * FROM users WHERE id = '$id'");
    return mysqli_fetch_array($query);
}

一些随机文件:

require_once("dbcon.php");

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

?>

我不觉得这种查询数据库和显示信息的方法是最有效或最有效的方法。我阅读了this关于使用类来篡改数据库和调用我在类中创建的函数的文章。

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

我也想知道将最佳方式存储到数据库的连接方式是什么,以及是否有关于如何设置它的任何教程。

我希望你明白这一点。

3 个答案:

答案 0 :(得分:4)

你可以这样做: -

<强> Dbconnection.php: -

<?php
Class DbConnection{
    function getdbconnect(){
        $conn = mysqli_connect("host","username","password","database") or die("Couldn't connect");

        return $conn;
    }
}
?>

<强> Function.php: -

<?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));
?>

注意: - 这是一个示例,请根据您的要求更改值并获取结果。

答案 1 :(得分:0)

<?php

class DatabaseConnection
{
    private $host       = "127.0.0.1";
    private $dbname     = "online_english";
    private $dbUsername = "root";
    private $dbPass     = "";
    private $charset    = 'utf8mb4';
    private $dsn;

    public function tryConnect(){
        try{
            $this->dsn = "mysql:host=$this->host;dbname=$this->dbname;charset=$this->charset";
            $DBH = new PDO($this->dsn,$this->dbUsername,$this->dbPass);
            $DBH->exec("set names utf8");
            $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $DBH;
        }
        catch (PDOException $e){
            $e->getMessage();
        }
    }
}
?>

答案 2 :(得分:0)

 <?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;
    }
}