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

标签 php mysql sql

我正在关注 Udemy 上有关构建登录表单的教程。一切顺利。

现在我正在尝试重用代码。我遇到的问题是当我试图查询数据库中的所有条目以获取网站总数时。你能给点建议吗?

这是我的计数函数(这是我在获取数据库条目总数以进行分页时遇到问题的地方):

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

    }

如果我使用它,我会列出所有 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;
        }
    }

}

数据库类。

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

    }

最佳答案

这部分好像不太对:

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

但我不太确定你想要什么。

我们可以将每个 id 附加到一个名为 $allWebsiteIds 的数组中:

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

这可能会给你你想要的。

关于php - 如何通过id查询数据库中的所有条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22669995/

相关文章:

php - 拉维尔 : How to insert the result queried from MongoDB into MySQL?

sql - 选择成二维数组

sql - 在 ORACLE 中,有没有一种方法可以使用两个表将多行行连接成一个行,其中最终值用逗号分隔?

SQL Server 使用 OPENJSON 解析嵌套 json

mysql - 在 Windows 中为 Ruby on Rails 设置 Mysql

php - 将explode与php和mysql一起使用

PHP:如何检查和安装 mysqlnd_qc

php - 使用set_error_handler多次包含错误

javascript - 创建数据的多维数组不会在 javascript 上生成数组

php - 检查是否设置了cookie,如果没有则输出脚本