数据库类,OOP - 连接到mysql

时间:2015-07-01 12:15:45

标签: php mysql database pdo bindparam

这是数据库类:

DB.php

<?php
    class DB {
        public static $instance = null;

        private     $_pdo = null,
                    $_query = null,
                    $_error = false,
                    $_results = null,
                    $_count = 0;

        private function __construct() {
            try {
                $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));
            } catch(PDOExeption $e) {
                die($e->getMessage());
            }
        }

        public static function getInstance() {
            // Already an instance of this? Return, if not, create.
            if(!isset(self::$instance)) {
                self::$instance = new DB();
            }
            return self::$instance;
        }

        public function query($sql, $params = array()) {

            $this->_error = false;

            if($this->_query = $this->_pdo->prepare($sql)) {
                $x = 1;
                if(count($params)) {
                    foreach($params as $param) {
                        $this->_query->bindValue($x, $param);
                        $x++;
                    }
                }

                if($this->_query->execute()) {
                    $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                    $this->_count = $this->_query->rowCount();
                } else {
                    $this->_error = true;
                }
            }

            return $this;
        }

        public function get($table, $where) {
            return $this->action('SELECT *', $table, $where);
        }

        public function delete($table, $where) {
            return $this->action('DELETE', $table, $where);
        }

        public function action($action, $table, $where = array()) {
            if(count($where) === 3) {
                $operators = array('=', '>', '<', '>=', '<=');

                $field      = $where[0];
                $operator   = $where[1];
                $value      = $where[2];

                if(in_array($operator, $operators)) {
                    $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";

                    if(!$this->query($sql, array($value))->error()) {
                        return $this;
                    }

                }

                return false;
            }
        }

        public function insert($table, $fields = array()) {
            $keys   = array_keys($fields);
            $values = null;
            $x      = 1;

            foreach($fields as $value) {
                $values .= "?";
                if($x < count($fields)) {
                    $values .= ', ';
                }
                $x++;
            }

            $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";

            if(!$this->query($sql, $fields)->error()) {
                return true;
            }

            return false;
        }

        public function update($table, $id, $fields = array()) {
            $set    = null;
            $x      = 1;

            foreach($fields as $name => $value) {
                $set .= "{$name} = ?";
                if($x < count($fields)) {
                    $set .= ', ';
                }
                $x++;
            }

            $sql = "UPDATE users SET {$set} WHERE id = {$id}";

            if(!$this->query($sql, $fields)->error()) {
                return true;
            }

            return false;
        }

        public function results() {
            // Return result object
            return $this->_results;
        }

        public function first() {
            return $this->_results[0];
        }

        public function count() {
            // Return count
            return $this->_count;
        }

        public function error() {
            return $this->_error;
        }
    }

我正在寻找这种数据库方法,它似乎非常实用和有用。我是oop的初学者,还在学习。 requestQuote看起来像这样:

如何在这样的查询中bindParam?

requestQuote = DB::getInstance()->query("");(表格DB.class)

这是我现在的代码:

$request = "";
    if ($_POST) {
        $request = $_POST["request"];
    } else if (isset($_GET["request"])) {
        $request = $_GET["request"];
    }

$requestQuote="%" . $request . "%";
            $sql = $conn -> prepare("SELECT * FROM users WHERE concat(name, ' ',lastname, ' ', user_id) LIKE :request limit " . (($page * 50)-50) . ",50");
            $sql->bindParam(":request", $requestQuote);
            $sql -> execute();
            $results = $sql -> fetchAll(PDO::FETCH_OBJ);

当我这样说时,分页就起作用了。但是我需要搜索表单...而且它不会起作用......

$sql= DB::getInstance()->query(
    "SELECT * FROM users
     WHERE (category='admin')
     LIMIT " . (($page* 5)-5) . ",5");

2 个答案:

答案 0 :(得分:1)

@Paul很接近,但你还有一个问题:

检查课程的这一部分:

$x = 1;
if(count($params)) {
   foreach($params as $param) {
       $this->_query->bindValue($x, $param);
       $x++;
    }
}

它不与命名占位符绑定,您需要更改代码:

$limit = ($page * 50)-50;
$params = array('%lolcats%', $limit);
$query = 
   "SELECT * FROM users 
    WHERE concat(name, ' ',lastname, ' ', user_id) 
    LIKE ? 
    LIMIT ?,50";
$results = DB::getInstance()->query($query, $params);

或更改类代码以按占位符绑定,类似于以下行:

#$params = array(':request' =>'%lolcats%', ':limit'=>$limit);
if(count($params)) {
   foreach($params as $key=>$value) {
       $this->_query->bindValue($key, $value);
    }
}

答案 1 :(得分:0)

查看此类,query函数的第二个参数是可选的参数数组,因此请使用此参数传递请求的参数:

$params = array(':request' => 'lolcats');
$limit = $page - 1 * 50;
$query = sprintf(
   "SELECT * FROM users 
    WHERE concat(name, ' ',lastname, ' ', user_id) 
    LIKE :request 
    LIMIT %d,50",
    $limt
);
$results = DB::getInstance()->query($query, $params);