使用mysqli

时间:2018-07-11 01:12:30

标签: php mysqli

我正在使用mysqli查询项目数据库。我试图从数据库中的项目中创建一个数组,但是卡住了。这是我到目前为止所拥有的。

$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'test';

$connection = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

if ($query = $connection->prepare('SELECT name, due_date, complete FROM items WHERE user_id = ?')) {
    $query->bind_param('i', $_SESSION['id']);
    $query->execute(); 
    $query->store_result();
    //var_dump($query->num_rows);
    if ($query->num_rows > 0) {
        $query->bind_result($name, $due_date, $complete);
        //$query->fetch();

        while ($query->fetch()) {

       }
    }
    $query->close();

}

我完全不确定如何将其转换为数组以用于我的项目列表中的foreach循环中。

1 个答案:

答案 0 :(得分:1)

如果您有mysqlnd,只需在->get_result()之后使用execute()

$query = $connection->prepare('SELECT name, due_date, complete FROM items WHERE user_id = ?');
$query->bind_param('i', $_SESSION['id']);
$query->execute();
$result = $query->get_result();
$rows = $result->fetch_all(MYSQLI_ASSOC); // fetch as associative

// then make your foreach or whatnot
foreach ($rows as $row) {
    // echo $row['name'];
}

如果您不希望立即全部加载它们,仍然可以使用while + fetch组合:

while ($row = $result->fetch_assoc()) {
    // echo $row['name']
    // $data[] = $row;
    // or whatever you need to do
}