正确调用PHP mysqli_fetch_array()

时间:2019-03-22 17:18:30

标签: php

我的连接通过方法DB.connect.php在类mysqli_connect中传递。如何在我的while周期内正确调用函数mysqli_fetch_array()

我的代码:

class DB_Functions {

private $conn;

// constructor
function __construct() {
    require_once 'DB_connect.php';
    // connecting to database
    $db = new Db_Connect();
    $this->conn = $db->connect();
} ...

...
public function getCount($date1, $date2) {

    $stmt = $this->conn->prepare("SELECT * FROM Sales WHERE date_of_sell >= ? AND date_of_sell <= ? ");

    $stmt->bind_param("ss", $date1, $date2);

    $stmt->execute();

    $stmt->store_result();
    // $count=5;
    //
    $count = $stmt->num_rows;

    if ($stmt->num_rows > 0) {
         while ($row = ???) {
             $count = $count + 1;
       }
    }

    $stmt->close();
    return $count;
  }
}

1 个答案:

答案 0 :(得分:0)

如果我对您的问题理解正确,那么您想在执行sql查询后返回行数。如果是这样,请尝试以下操作:

public function getCount($date1, $date2) {
    $stmt = $this->conn->prepare("SELECT * FROM Sales WHERE date_of_sell >= ? AND date_of_sell <= ? ");
    $stmt->bind_param("ss", $date1, $date2);
    $stmt->execute(); // Executes a prepared Query

    // Solution 1
    $arr = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    if(!$arr) exit('No rows');
    var_export($arr);
    $stmt->close();

    // Solution 2
    $result = $stmt->get_result();
    if($result->num_rows === 0) exit('No rows');
    $tmp = [];
    while($row = $result->fetch_assoc()) {
        $tmp[] = [
            "field1" => $row['field1'], 
            "field2" => $row['field2'], 
            "field3" => $row['field3']
        ];
    }
    $stmt->close(); // Closes a previously opened database connection
    return $tmp;
}