PHP:如何在MVC中使用mysqli_escape_字符串?

PHP:如何在MVC中使用mysqli_escape_字符串?,php,mysqli,Php,Mysqli,db.php cn.php class dbconnect{ public function connect(){ $connection = mysqli_connect($host,$user,$pass,$db); return $connection; } } index.php include 'db.php'; class dao extends dbconnect { private $conn; publ

db.php

cn.php

class dbconnect{
    public function connect(){
         $connection = mysqli_connect($host,$user,$pass,$db); 
         return $connection;
     }
}
index.php

include 'db.php';
class dao extends dbconnect {
    private $conn; 
    public function __construct() { 
       $dbcon = new parent(); 
       $this->conn = $dbcon->connect();
    }

    public function select( $table , $where='' , $other='' ){
       ...
    }
   }
如何转义$username=$\u POST['user\u name'];在从数据库中选择之前


我想连接到数据库一次,并永远使用它

这是我刚刚发现的一个好类!它帮助您完成所有数据库位,并使用MySQLi


在查询中使用值之前,不能在函数中使用mysqli\u escape\u字符串吗?不过老实说,你不需要使用mysqli\u escape\u字符串。将其作为值绑定到查询不需要转义它。逃避它意味着你可能在做别的错事。@David,我不明白。你能再解释一下吗?具体解释一下什么?如果需要使用该函数,请使用它。但是,如果您将值正确绑定到查询,而不是尝试将值作为代码执行,那么您真的不需要使用它。如果你给出一个更完整的问题示例,也许你遇到的问题会更清楚。您尝试在何处使用该函数以及该函数是如何失败的?@David我想将该函数用于SQL注入该函数对于防止SQL注入不可靠。例如:防止SQL注入的方法是不将用户可修改的值作为代码执行,而不是在执行之前将这些值转换为安全代码。SQL注入很简单。不要将用户输入作为代码执行。有关更多信息,请参阅:
include 'cn.php';

if(isset($_POST['login'])){
    $username = $_POST['user_name']; // HOW ESCAPE THIS LINE ?

    $d = new dao();
    $sel = $d->select("users" , ... ) or die('error from here');
    ...
}
<?php
if ( !class_exists( 'DB' ) ) {
    class DB {
        public function __construct($user, $password, $database, $host = 'localhost') {
            $this->user = $user;
            $this->password = $password;
            $this->database = $database;
            $this->host = $host;
        }
        protected function connect() {
            return new mysqli($this->host, $this->user, $this->password, $this->database);
        }
        public function query($query) {
            $db = $this->connect();
            $result = $db->query($query);

            while ( $row = $result->fetch_object() ) {
                $results[] = $row;
            }

            return $results;
        }
        public function insert($table, $data, $format) {
            // Check for $table or $data not set
            if ( empty( $table ) || empty( $data ) ) {
                return false;
            }

            // Connect to the database
            $db = $this->connect();

            // Cast $data and $format to arrays
            $data = (array) $data;
            $format = (array) $format;

            // Build format string
            $format = implode('', $format); 
            $format = str_replace('%', '', $format);

            list( $fields, $placeholders, $values ) = $this->prep_query($data);

            // Prepend $format onto $values
            array_unshift($values, $format); 
            // Prepary our query for binding
            $stmt = $db->prepare("INSERT INTO {$table} ({$fields}) VALUES ({$placeholders})");
            // Dynamically bind values
            call_user_func_array( array( $stmt, 'bind_param'), $this->ref_values($values));

            // Execute the query
            $stmt->execute();

            // Check for successful insertion
            if ( $stmt->affected_rows ) {
                return true;
            }

            return false;
        }
        public function update($table, $data, $format, $where, $where_format) {
            // Check for $table or $data not set
            if ( empty( $table ) || empty( $data ) ) {
                return false;
            }

            // Connect to the database
            $db = $this->connect();

            // Cast $data and $format to arrays
            $data = (array) $data;
            $format = (array) $format;

            // Build format array
            $format = implode('', $format); 
            $format = str_replace('%', '', $format);
            $where_format = implode('', $where_format); 
            $where_format = str_replace('%', '', $where_format);
            $format .= $where_format;

            list( $fields, $placeholders, $values ) = $this->prep_query($data, 'update');

            //Format where clause
            $where_clause = '';
            $where_values = '';
            $count = 0;

            foreach ( $where as $field => $value ) {
                if ( $count > 0 ) {
                    $where_clause .= ' AND ';
                }

                $where_clause .= $field . '=?';
                $where_values[] = $value;

                $count++;
            }
            // Prepend $format onto $values
            array_unshift($values, $format);
            $values = array_merge($values, $where_values);
            // Prepary our query for binding
            $stmt = $db->prepare("UPDATE {$table} SET {$placeholders} WHERE {$where_clause}");

            // Dynamically bind values
            call_user_func_array( array( $stmt, 'bind_param'), $this->ref_values($values));

            // Execute the query
            $stmt->execute();

            // Check for successful insertion
            if ( $stmt->affected_rows ) {
                return true;
            }

            return false;
        }
        public function select($query, $data, $format) {
            // Connect to the database
            $db = $this->connect();

            //Prepare our query for binding
            $stmt = $db->prepare($query);

            //Normalize format
            $format = implode('', $format); 
            $format = str_replace('%', '', $format);

            // Prepend $format onto $values
            array_unshift($data, $format);

            //Dynamically bind values
            call_user_func_array( array( $stmt, 'bind_param'), $this->ref_values($data));

            //Execute the query
            $stmt->execute();

            //Fetch results
            $result = $stmt->get_result();

            //Create results object
            while ($row = $result->fetch_object()) {
                $results[] = $row;
            }
            return $results;
        }
        public function delete($table, $id) {
            // Connect to the database
            $db = $this->connect();

            // Prepary our query for binding
            $stmt = $db->prepare("DELETE FROM {$table} WHERE ID = ?");

            // Dynamically bind values
            $stmt->bind_param('d', $id);

            // Execute the query
            $stmt->execute();

            // Check for successful insertion
            if ( $stmt->affected_rows ) {
                return true;
            }
        }
        private function prep_query($data, $type='insert') {
            // Instantiate $fields and $placeholders for looping
            $fields = '';
            $placeholders = '';
            $values = array();

            // Loop through $data and build $fields, $placeholders, and $values         
            foreach ( $data as $field => $value ) {
                $fields .= "{$field},";
                $values[] = $value;

                if ( $type == 'update') {
                    $placeholders .= $field . '=?,';
                } else {
                    $placeholders .= '?,';
                }

            }

            // Normalize $fields and $placeholders for inserting
            $fields = substr($fields, 0, -1);
            $placeholders = substr($placeholders, 0, -1);

            return array( $fields, $placeholders, $values );
        }
        private function ref_values($array) {
            $refs = array();
            foreach ($array as $key => $value) {
                $refs[$key] = &$array[$key]; 
            }
            return $refs; 
        }
    }
}
//Your config.php file:
require 'classes/db.php';
$db = new DB('root', 'password here', 'test'); (host is default localhost)