0

My connection passes in class DB.connect.php with method mysqli_connect. How can I correct to call a function mysqli_fetch_array() inside my while cycle?

My code:

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;
  }
}
double-beep
  • 5,031
  • 17
  • 33
  • 41
  • Check https://stackoverflow.com/questions/14456529/mysqli-fetch-array-while-loop-columns – Alex Mar 22 '19 at 17:26

1 Answers1

0

If I understood your question right, you want to return the number of rows after executing your sql query. If so, try this:

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;
}
toh19
  • 1,083
  • 10
  • 21
  • No man, I wanna call function mysqli_fetch_array() inside while. But if i write mysqli_fetch_array($stmt) there's will be mistake, cause this function works with 2 arguments. It is my question. How to call this function in my opinion? – Stanislav Lukyanov Mar 22 '19 at 20:34
  • @StanislavLukyanov - I update my code, inside the while loop change the `field1`.. with the name of the fields from your select query – toh19 Mar 22 '19 at 20:42