简体   繁体   English

如何使用循环从查询中获取结果

[英]How to get results from query using loop

I'm trying to make a query using procedural PHP. 我正在尝试使用过程PHP进行查询。 I've used OOP mostly. 我主要使用OOP。 It's not giving correct results. 它没有给出正确的结果。 I want to get all records from table offers and then make an array width all offer ids in it. 我想从表商品中获取所有记录,然后在其中提供所有商品ID的数组宽度。

When print_r($sql->getNumRows()) - it gives me correct count. print_r($sql->getNumRows()) -它给我正确的计数。 But I want to put ids in array and when I print_r(count($all)) - count is bigger. 但是我想将id放入数组中,当我print_r(count($all)) -计数更大时。

What is proper way to do that? 这样做的正确方法是什么?

My code is: 我的代码是:

$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

Any reason you aren't using MySQL Improved Extension ( http://php.net/manual/en/book.mysqli.php )? 有什么原因不使用MySQL改进的扩展( http://php.net/manual/zh/book.mysqli.php )?

I believe the way you are trying to do it has been deprecated. 我相信您尝试执行此操作的方式已被弃用。 You could try something like this: 您可以尝试这样的事情:

<?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