This question already has answers here:
LIMIT keyword on MySQL with prepared statement [duplicate]
                                
                                    (2个答案)
                                
                        
                                3年前关闭。
            
                    
我开始使用PDOMySQL而不是mysqli
因此,我尝试定义此简单函数:

public function getIntro($table) {
            $stmt = $this->db->prepare("SELECT * FROM $table ORDER BY rand() LIMIT ?");
            $stmt->execute(array(6));
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        }


但是,这样做时,函数将返回一个空数组。考虑到与数据库的连接正常工作,错误在哪里?

谢谢

最佳答案

尝试这个:

public function getIntro($table) {
        $stmt = $this->db->prepare("SELECT * FROM $table ORDER BY rand() LIMIT ?");
        $stmt->bindValue(1, 6);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }


或这个:

public function getIntro($table) {
            $stmt = $this->db->prepare("SELECT * FROM $table ORDER BY rand() LIMIT :limit");
            $stmt->execute(array(':limit' => 6));
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        }

关于php - 使用PDO和MySql代替mysqli ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36925801/

10-11 03:30