簡體   English   中英

如何使用循環從查詢中獲取結果

[英]How to get results from query using loop

我正在嘗試使用過程PHP進行查詢。 我主要使用OOP。 它沒有給出正確的結果。 我想從表商品中獲取所有記錄,然后在其中提供所有商品ID的數組寬度。

print_r($sql->getNumRows()) -它給我正確的計數。 但是我想將id放入數組中,當我print_r(count($all)) -計數更大時。

這樣做的正確方法是什么?

我的代碼是:

$sql->query("SELECT id  FROM offers ORDER BY id ASC");
if ($row=$sql->getNumRows()) {
    for ($i=0; $i< $sql->getNumRows(); $i++) { 
        $all[]= $sql->getRow($i);
    }

    print_r($sql->getNumRows()); //this prints correct number
    print_r(count($all)); //this prints bigger count

有什么原因不使用MySQL改進的擴展( http://php.net/manual/zh/book.mysqli.php )?

我相信您嘗試執行此操作的方式已被棄用。 您可以嘗試這樣的事情:

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$query = "SELECT id  FROM offers ORDER BY id ASC";

$allRows = array();
if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {   
        //Store the row in an array for later use
        $allRows[] = $row;
    }

    /* free result set */
    $result->free();
}

/* close connection */
$mysqli->close();

print_r(count($allRows));
print_r($allRows);

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM