I am using below code to get data from my database which matches the user input year and month.
connection :
class ConnectDB{
private $servername;
private $username;
private $password;
private $dbname;
protected function connect(){
$this->servername ="localhost";
$this->username ="root";
$this->password ="";
$this->dbname ="dbexpense";
$conn = new mysqli($this->servername,$this->username,$this->password,$this->dbname);
if($conn -> connect_error) {
die("connection failed:".$conn-> connect_error);
}
return $conn;
}
}
Class to Pull data:
<?php
class SelectAMonthGet extends ConnectDB {
var $year;
var $month;
function __construct( ){
$this->year = $_POST['year'];
$this->month = $_POST['analyze_options_month'];
}
protected function SelectAMonthGetData(){
$year = $this->year;
$month = $this->month;
$sql = $this->connect()->prepare("SELECT * FROM wp_myexpenses WHERE YEAR(date) = ? AND MONTH(date) = ? order by date,id");
$sql->bind_param("ss",$year,$month);
$result = $sql ->execute();
$numRows = $result->num_rows;
if($numRows > 0) {
while ($row = $result->fetch_assoc()){
$data[] = $row;
}
return $data;
}
}
}
?>
But it not showing up any result even though there is data in DB.
I am able to get a result when I use the code without a prepared statement like below:
Code without prepared statement(working):
class SelectAMonthGet extends ConnectDB {
var $year;
var $month;
function __construct( ){
$this->year = $_POST['year'];
$this->month = $_POST['analyze_options_month'];
}
protected function SelectAMonthGetData(){
$year = $this->year;; $month = $this->month;
$sql = "SELECT * FROM wp_myexpenses WHERE YEAR(date) = '$year' AND MONTH(date) = '$month' order by date,id";
$result = $this->connect()->query($sql);
$numRows = $result->num_rows;
if($numRows > 0) {
while ($row = $result->fetch_assoc()){
$data[] = $row;
}
return $data;
}
}
}
?>
I would like to use a prepared statement to avoid SQL injections. I am unable to understand what's wrong with my code? Can someone guide me here please?
Update: As suggested by ADyson in comments, enabled error reporting. Its giving below error :
Notice: Trying to get property of non-object in **** on line 34
Line 34:
$numRows = $result->num_rows;
Update:
Changed the code to include get_result() like below
protected function SelectAMonthGetData(){
$year = $this->year;
$month = $this->month;
$sql = $this->connect()->prepare("SELECT * FROM wp_myexpenses WHERE YEAR(date) = ? AND MONTH(date) = ? order by date,id");
$sql->bind_param("ss",$year,$month);
$sql ->execute();
$result = $sql->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
while ($row = $result->fetch_assoc()){
$data[] = $row;
}
return $data;
}
}
But now its tarted giving error:
Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::get_result() in ****:28
Upon checking some of the solution, error is due to mysqlnd driver not enabled. This is true in my case. Will there any alternate solution to get it ?