Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/235.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用对象的Mysqli连接_Php_Mysql_Mysqli - Fatal编程技术网

Php 使用对象的Mysqli连接

Php 使用对象的Mysqli连接,php,mysql,mysqli,Php,Mysql,Mysqli,我刚开始将我的项目从mysql切换到mysqli。我所做的就是创建一个类db和函数connect。如何创建对象并重用它 这是我的代码: 类别数据库: class db { //global var session private $biz; //constructor function db (&$b) { $this->biz = $b; $this->connect();

我刚开始将我的项目从mysql切换到mysqli。我所做的就是创建一个类db和函数connect。如何创建对象并重用它

这是我的代码:

类别数据库:

class db {

    //global var session
    private $biz;

    //constructor
    function db (&$b) {
        $this->biz = $b;            
        $this->connect();
    }

    function connect() {
        mysqli_connect(
              $this->biz->_db['host']
            , $this->biz->_db['username']
            , $this->biz->_db['password']
                        ,$this->biz->_db['database']
        ) or die("Unable to connect to database");

        //$cont=mysqli_select_db($con,$this->biz->_db['database']) or die("Unable to select database: {$this->biz->_db['database']}");
        //return $connt;
    }       

    /*
     This function will perform a simple query and return all the results
     @return        object      Object containing the rows, num_rows and result

     @param string  $sql        The SQL query
    */
    function query($sql) {

            $result = new fetchQuery($sql);
            return $result;
    }

    /*
     This function will perform a query given the sql
     @return        object      Object containing num rows affected and result

     @param string  $sql        The SQL query
    */
    function updateQuery($sql) {
        return new updateQuery($sql);
    }

    /*
     This function will perform a query given the sql
     @return        object      Object containing num rows affected and result

     @param string  $sql        The SQL query
    */
    function insertQuery($sql) {    
        return new insertQuery($sql);
    }

    /*
     This function will perform a query given the sql
     @return        object      Object containing num rows affected and result

     @param string  $sql        The SQL query
    */
    function deleteQuery($sql) {
        return new deleteQuery($sql);
    }

    /*
     This function will automatically decide if data is being updated or inserted

     @param array   $data       The post object, key/value pairs , already validated
     @param string  $table      The table to be updated
    */       

    /*
     This function will perform an update query from the post data that has the correct form - fields matching table field names
     @return        object      Object containing num rows affected and result

     @param array   $data       The post object, key/value pairs , already validated
     @param string  $table      The table to be updated
    */
    function autoUpdate($data, $table,$wheredata) {

        //id is required, return false if not found
        if (!isset($wheredata)) 
        {
            return false;
        }  

        $sql = "
            UPDATE
                `$table`
            SET
        ";

        foreach ($data as $key => $value) {          
                $sql .= " `$key` = '$value' ,";     
        }

        //remove extra comma
        $sql = substr($sql, 0, (strlen($sql) - 1));         
        $sql .= " WHERE 0=0 ";

        foreach ($wheredata as $key => $value) {
        $sql .= " and `$key` = '$value' ";
        }

        return new updateQuery($sql);
    }

    /*
     This function will perform an insert query from the matching form table
     @return        object      Object containing num rows affected and result

     @param array   $data       The post object, key/value pairs , already validated
     @param string  $table      The table to be updated
    */
    function autoInsert($data, $table, $validate = false)
    {
        $_fields = array();
        $_values = array();

        foreach ($data as $field => $value) {
            $_fields[] = $field;
            $_values[] = $value;
        }

        $sql = "
            INSERT INTO
                `$table`
                    (
        ";

        foreach($_fields as $field) {
            $sql .= "`$field` ,";
        }

        //remove extra comma
        $sql = substr($sql, 0, (strlen($sql) - 1));

        $sql .= "
            ) VALUES (
        ";

        foreach($_values as $value) {
            $sql .= "'$value' ,";
        }

        //remove extra comma
        $sql = substr($sql, 0, (strlen($sql) - 1));

        $sql .= "
            )
        ";

        return new insertQuery($sql);
    }

    /*
     This function will perform an auto delete query from the matching form table
     @return        object      Object containing num rows affected and result

     @param int     $id         The related id
     @param string  $table      The table to be affected
    */
    function autoDelete($sql) {         
        return new deleteQuery($sql);       }
}
class fetchQuery {

    public $result;
    public $num = 0;
    public $rows = array();
    public $error = false;

    function fetchQuery($sql) {

        $this->result = mysql_query($sql);    

        if ($this->result) {
            $this->num = mysql_num_rows($this->result);
            if ($this->num) {
                while($row = mysql_fetch_assoc($this->result)) {
                    $this->rows[] = $row;
                }
            } else {
                $this->result = false;
            }
        } else {
            $this->result = false;
            $this->error  = mysql_error();
        }
    }
获取查询:

class db {

    //global var session
    private $biz;

    //constructor
    function db (&$b) {
        $this->biz = $b;            
        $this->connect();
    }

    function connect() {
        mysqli_connect(
              $this->biz->_db['host']
            , $this->biz->_db['username']
            , $this->biz->_db['password']
                        ,$this->biz->_db['database']
        ) or die("Unable to connect to database");

        //$cont=mysqli_select_db($con,$this->biz->_db['database']) or die("Unable to select database: {$this->biz->_db['database']}");
        //return $connt;
    }       

    /*
     This function will perform a simple query and return all the results
     @return        object      Object containing the rows, num_rows and result

     @param string  $sql        The SQL query
    */
    function query($sql) {

            $result = new fetchQuery($sql);
            return $result;
    }

    /*
     This function will perform a query given the sql
     @return        object      Object containing num rows affected and result

     @param string  $sql        The SQL query
    */
    function updateQuery($sql) {
        return new updateQuery($sql);
    }

    /*
     This function will perform a query given the sql
     @return        object      Object containing num rows affected and result

     @param string  $sql        The SQL query
    */
    function insertQuery($sql) {    
        return new insertQuery($sql);
    }

    /*
     This function will perform a query given the sql
     @return        object      Object containing num rows affected and result

     @param string  $sql        The SQL query
    */
    function deleteQuery($sql) {
        return new deleteQuery($sql);
    }

    /*
     This function will automatically decide if data is being updated or inserted

     @param array   $data       The post object, key/value pairs , already validated
     @param string  $table      The table to be updated
    */       

    /*
     This function will perform an update query from the post data that has the correct form - fields matching table field names
     @return        object      Object containing num rows affected and result

     @param array   $data       The post object, key/value pairs , already validated
     @param string  $table      The table to be updated
    */
    function autoUpdate($data, $table,$wheredata) {

        //id is required, return false if not found
        if (!isset($wheredata)) 
        {
            return false;
        }  

        $sql = "
            UPDATE
                `$table`
            SET
        ";

        foreach ($data as $key => $value) {          
                $sql .= " `$key` = '$value' ,";     
        }

        //remove extra comma
        $sql = substr($sql, 0, (strlen($sql) - 1));         
        $sql .= " WHERE 0=0 ";

        foreach ($wheredata as $key => $value) {
        $sql .= " and `$key` = '$value' ";
        }

        return new updateQuery($sql);
    }

    /*
     This function will perform an insert query from the matching form table
     @return        object      Object containing num rows affected and result

     @param array   $data       The post object, key/value pairs , already validated
     @param string  $table      The table to be updated
    */
    function autoInsert($data, $table, $validate = false)
    {
        $_fields = array();
        $_values = array();

        foreach ($data as $field => $value) {
            $_fields[] = $field;
            $_values[] = $value;
        }

        $sql = "
            INSERT INTO
                `$table`
                    (
        ";

        foreach($_fields as $field) {
            $sql .= "`$field` ,";
        }

        //remove extra comma
        $sql = substr($sql, 0, (strlen($sql) - 1));

        $sql .= "
            ) VALUES (
        ";

        foreach($_values as $value) {
            $sql .= "'$value' ,";
        }

        //remove extra comma
        $sql = substr($sql, 0, (strlen($sql) - 1));

        $sql .= "
            )
        ";

        return new insertQuery($sql);
    }

    /*
     This function will perform an auto delete query from the matching form table
     @return        object      Object containing num rows affected and result

     @param int     $id         The related id
     @param string  $table      The table to be affected
    */
    function autoDelete($sql) {         
        return new deleteQuery($sql);       }
}
class fetchQuery {

    public $result;
    public $num = 0;
    public $rows = array();
    public $error = false;

    function fetchQuery($sql) {

        $this->result = mysql_query($sql);    

        if ($this->result) {
            $this->num = mysql_num_rows($this->result);
            if ($this->num) {
                while($row = mysql_fetch_assoc($this->result)) {
                    $this->rows[] = $row;
                }
            } else {
                $this->result = false;
            }
        } else {
            $this->result = false;
            $this->error  = mysql_error();
        }
    }

请给我一个使用connect函数创建fetch查询的解决方案。

您可以创建一个类似于策略的基本函数来处理此类场景。因此,如果您单独包含函数文件,您的数据库将动态连接,您可以使用连接到数据库的变量来使用它

您可以有两个文件,然后可以像这样执行场景

db.php

<?php
class DB {
    function __construct(){
        $username='root';
        $password='';
        $host='localhost';
        $db='store';
        $this->connection = mysqli_connect($username,$password,$host,$db);
        if(mysqli_connect_errno){
            echo "Failed to connect to MYSQL: " . mysqli_connect_error();
        }
    }

    function fetchData(){
        $get_query = "SELECT * FROM TABLE"
        $result = mysqli_query($this->connection, $get_query);
    }

}
?>
<?php
include('db.php'); // Include the DB file over this line
$conn= new DB(); // Initialize the class that we have created
$conn->fetchData();// This query will select all the data and return it.
?>

您可以调用页面中的函数,如下所示

我们创建的类的用法

listpage.php

<?php
class DB {
    function __construct(){
        $username='root';
        $password='';
        $host='localhost';
        $db='store';
        $this->connection = mysqli_connect($username,$password,$host,$db);
        if(mysqli_connect_errno){
            echo "Failed to connect to MYSQL: " . mysqli_connect_error();
        }
    }

    function fetchData(){
        $get_query = "SELECT * FROM TABLE"
        $result = mysqli_query($this->connection, $get_query);
    }

}
?>
<?php
include('db.php'); // Include the DB file over this line
$conn= new DB(); // Initialize the class that we have created
$conn->fetchData();// This query will select all the data and return it.
?>

我希望我对代码的解释是清楚的,你可以很好地理解它,并继续你的项目代码的飞行


快乐编码:)

您可以创建一个基本的函数式策略来处理这种类型的场景。因此,如果您单独包含函数文件,您的数据库将动态连接,您可以使用连接到数据库的变量来使用它

您可以有两个文件,然后可以像这样执行场景

db.php

<?php
class DB {
    function __construct(){
        $username='root';
        $password='';
        $host='localhost';
        $db='store';
        $this->connection = mysqli_connect($username,$password,$host,$db);
        if(mysqli_connect_errno){
            echo "Failed to connect to MYSQL: " . mysqli_connect_error();
        }
    }

    function fetchData(){
        $get_query = "SELECT * FROM TABLE"
        $result = mysqli_query($this->connection, $get_query);
    }

}
?>
<?php
include('db.php'); // Include the DB file over this line
$conn= new DB(); // Initialize the class that we have created
$conn->fetchData();// This query will select all the data and return it.
?>

您可以调用页面中的函数,如下所示

我们创建的类的用法

listpage.php

<?php
class DB {
    function __construct(){
        $username='root';
        $password='';
        $host='localhost';
        $db='store';
        $this->connection = mysqli_connect($username,$password,$host,$db);
        if(mysqli_connect_errno){
            echo "Failed to connect to MYSQL: " . mysqli_connect_error();
        }
    }

    function fetchData(){
        $get_query = "SELECT * FROM TABLE"
        $result = mysqli_query($this->connection, $get_query);
    }

}
?>
<?php
include('db.php'); // Include the DB file over this line
$conn= new DB(); // Initialize the class that we have created
$conn->fetchData();// This query will select all the data and return it.
?>

我希望我对代码的解释是清楚的,你可以很好地理解它,并继续你的项目代码的飞行


快乐编码:)

制作一个如下所示的结构并尝试

数据库配置:dbconfig.php

<?php
$glob['dbhost'] = 'localhost'; 
$glob['dbusername'] = 'username'; 
$glob['dbpassword'] =  'password'; 
$glob['dbdatabase'] = 'database';  
?>

数据库类:Database.Class.php

<?php

class database {

var $_sql           = '';   
/** @var Internal variable to hold the connector resource */
var $_resource      = '';
/** @var Internal variable to hold the query result*/
var $_result        = ''; 

/**
* Database object constructor
* @param string Database host
* @param string Database user name
* @param string Database user password
* @param string Database name
*/
function database() {
    global $glob;
    $host = $glob['dbhost'];
    $user = $glob['dbusername'];
    $pass = $glob['dbpassword'];
    $db = $glob['dbdatabase'];
    $this->_resource = @mysqli_connect( $host, $user, $pass, $db );
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    else{
        echo "Could not connect to the database!";
        exit;
    }               
}

/**
* Execute the query
* @return mixed A database resource if successful, FALSE if not.
*/
function query($sql) {
    $_sql = $sql;
    return $_result = @mysqli_query($this->_resource, $_sql);               
}

function fetchArray($result) {
    return @mysqli_fetch_array($result);
}

function fetchAssoc($result) {
    return @mysqli_fetch_assoc($result);
}
}
?>

项目配置:Configuration.php

<?php
session_start();
ob_start("ob_gzhandler");
@ob_gzhandler();
error_reporting(E_ERROR);

require_once('dbconfig.php');

require_once('database.class.php');
$dbclass = new database();
?>

任何项目文件代码:

<?php
require('configuration.php');

$sqltepm="SELECT * FROM tblname";
$restepm=$dbclass->query($sqltepm);
while($row=$dbclass->fetchArray($restepm)){
    extract($row);
}
?>

制作一个如下所示的结构并尝试

数据库配置:dbconfig.php

<?php
$glob['dbhost'] = 'localhost'; 
$glob['dbusername'] = 'username'; 
$glob['dbpassword'] =  'password'; 
$glob['dbdatabase'] = 'database';  
?>

数据库类:Database.Class.php

<?php

class database {

var $_sql           = '';   
/** @var Internal variable to hold the connector resource */
var $_resource      = '';
/** @var Internal variable to hold the query result*/
var $_result        = ''; 

/**
* Database object constructor
* @param string Database host
* @param string Database user name
* @param string Database user password
* @param string Database name
*/
function database() {
    global $glob;
    $host = $glob['dbhost'];
    $user = $glob['dbusername'];
    $pass = $glob['dbpassword'];
    $db = $glob['dbdatabase'];
    $this->_resource = @mysqli_connect( $host, $user, $pass, $db );
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    else{
        echo "Could not connect to the database!";
        exit;
    }               
}

/**
* Execute the query
* @return mixed A database resource if successful, FALSE if not.
*/
function query($sql) {
    $_sql = $sql;
    return $_result = @mysqli_query($this->_resource, $_sql);               
}

function fetchArray($result) {
    return @mysqli_fetch_array($result);
}

function fetchAssoc($result) {
    return @mysqli_fetch_assoc($result);
}
}
?>

项目配置:Configuration.php

<?php
session_start();
ob_start("ob_gzhandler");
@ob_gzhandler();
error_reporting(E_ERROR);

require_once('dbconfig.php');

require_once('database.class.php');
$dbclass = new database();
?>

任何项目文件代码:

<?php
require('configuration.php');

$sqltepm="SELECT * FROM tblname";
$restepm=$dbclass->query($sqltepm);
while($row=$dbclass->fetchArray($restepm)){
    extract($row);
}
?>


首先,现在混合使用mysqli和mysql函数。第二,我认为这不是一个好的设计。为什么不创建一个数据库类,在其中所有事情都发生和存储?我想将其更改为mysqli,就像mysqli_query($con,$sql)。我的疑问是,从哪里创建$con以及如何访问fetchQuery函数首先,现在您混合了mysqli和mysql函数。第二,我认为这不是一个好的设计。为什么不创建一个数据库类,在那里所有的事情都会发生和存储?我想把它改成mysqli,就像mysqli_query($con,$sql)。我的疑问是,从哪里创建$con以及如何访问它到fetchQuery函数