我如何在PHP中使用fetchAll?

时间:2012-11-08 20:18:19

标签: php sql fetchall

我正在使用此语句来获取db

中列中的元素
$result = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

但尝试运行时出现此错误。

调用未定义的方法mysqli_stmt::fetchAll();

我需要添加到我的php文件中以包含该方法吗?

更新1:

class LoginAPI
{
private $db;

function __construct() 
{
    $this->db = new mysqli('xxx', 'xxx', 'xxx', 'xxx');
    $this->db->autocommit(FALSE);
}

function __destruct() 
{
    $this->db->close();
}

function login() 
{
    if(isset($_POST["lang"]))
    {
        $stmt = $this->db->prepare("SELECT code FROM locations");
        $stmt->execute();
        $stmt->bind_result($code);

        //while($stmt->fetch())
        //{
        //  result[] = "code"=>$code;
        //  break;
        //}
        $codeArr = array();
        $result = $stmt->fetch_all();//|PDO::FETCH_GROUP;




        sendResponse(200, json_encode($result));
        return true;
    }
    sendResponse(400, 'Invalid Request');
    return false;
}
}

1 个答案:

答案 0 :(得分:5)

你正在使用mysqli,而且你的声明不是结果。如果您有mysqli_result,则可以使用方法fetch_all()

但是,由于这是一个mysqli_stmt,您首先需要执行,然后在结果集上使用fetch_all()。见下面的例子

 $stmt = $this->db->prepare("SELECT code FROM locations");
 $stmt->execute();


//grab a result set
$resultSet = $stmt->get_result();

//pull all results as an associative array
$result = $resultSet->fetch_all();

注意:使用fetch_all,您无需将结果绑定为原始代码。