简体   繁体   English

如何通过ID查询数据库中的所有条目?

[英]How to query all entries from the database by id?

I was following this tutorial on Udemy about building login form. 我在Udemy上关注有关构建登录表单的教程。 Everything went well. 一切顺利。

Now I'm trying to reuse the code. 现在,我正在尝试重用代码。 The problem I'm having is when I'm trying to query all entries from a database in order to get a total number of websites. 我遇到的问题是,当我尝试查询数据库中的所有条目以获取网站总数时。 Could you please advise? 您能否提一些建议?

Here is my count function (this is where I'm having issues in obtaining a total number of entries to the database for pagination): 这是我的计数函数(这是在获取用于分页的数据库条目总数时遇到的问题):

function get_all_websites(){

        $all = array();

        $db = DB::getInstance();
        $all = $db->query("SELECT * FROM website");

        if(!$all->count()){
            echo 'No Websites available. Please check back later.';
        } else {
            foreach($all->results() as $all){
                $all->id = $all;
            }
        }

        return $all;

    }

    function get_websites_count(){

        return count(get_all_websites());

    }

if I use this I get all ID's listed. 如果我使用这个,我会列出所有ID。

function get_all_websites(){

    $all = array();

    $db = DB::getInstance();
    $all = $db->query("SELECT * FROM website");

    if(!$all->count()){
        echo 'No Websites available. Please check back later.';
    } else {
        foreach($all->results() as $all){
            echo $all->id;
        }
    }

}

Database class. 数据库类。

class DB{
        private static $_instance = null;
        private $_pdo,
                $_query,
                $_error = false,
                $_results,
                $_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(PDOException $e){
                die($e -> getMessage());
            }
        }

        public static function getInstance(){
            if(!isset(self::$_instance)) {
                self::$_instance = new DB();
            }
            return self::$_instance;
        }

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

            $this->_error = false;

            // Check if query has been prepared properly

            if($this->_query = $this->_pdo->prepare($sql)){

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

            // If the query has been prepared successfuly, store the result
                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 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;
        }

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

        // DELETING DATA FROM DATABASE
        public function delete($table, $where){
            return $this->action('DELETE', $table, $where);
        }

        // INSERTING DATA INTO DATABASE
        public function insert($table, $fields = array()){
                $keys = array_keys($fields);
                $values = '';
                $x = 1;

                foreach($fields as $field){
                    $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 results(){
            return $this->_results;
        }

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

            foreach($fields as $name => $value){
                $set .= "{$name} = ?";

                if($x < count($fields)){
                    $set .= ', ';
                }
                $x++;
            }


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

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

            return false;
        }

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

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

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

    }

This part doesn't seem right: 这部分似乎不正确:

    } else {
        foreach($all->results() as $all){
            $all->id = $all;
        }
    }
    return $all;

but I'm not exactly sure what you want. 但我不确定您想要什么。

We could append each id to an array called $allWebsiteIds: 我们可以将每个id附加到名为$ allWebsiteIds的数组中:

    } else {
        foreach($all->results() as $all){
            $allWebsiteIds[] = $all->id;
        }
    }
    return $allWebsiteIds;

That might give you what you want. 那可能会给你你想要的。

SQL provides built-in support for counting rows in a table. SQL提供了对计数表中行的内置支持。

SELECT COUNT(*) FROM ...

This is highly optimizable and avoids loading every row into PHP's memory. 这是高度可优化的,避免了将每一行加载到PHP的内存中。

Additionally, pay close attention to the construct of your loops; 另外,请密切注意循环的构造; specifically what it means to say: 具体说的意思是:

foreach($foo as $foo)

As part of your study, you should be able to say why that expression is almost never the intended one. 作为研究的一部分,您应该能够说出为什么这种表达几乎绝不是预期的表达。

There is a broader rule: Never mutate that which you are iterating over. 有一个更广泛的规则:切勿对要迭代的内容进行更改。

Why not use the select to count the rows? 为什么不使用select来计算行数?

SELECT COUNT(1) FROM website; 从网站中选择COUNT(1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM