I am new to mysqli and started trying to learn basic things. With respect to this i example (http://php.net/manual/en/mysqli-result.fetch-array.php) i was trying fetch_array. Here is my code.
$sqlGetChartData = "SELECT date, ratepersqft, location
FROM ratepersqft
WHERE project_id = 1";
$runGetChartData = $mysqli->query($sqlGetChartData);
while($rowGetChartData = $runGetChartData->fetch_array(MYSQLI_BOTH))
$arrGetChartData[] = $rowGetChartData;
print "<pre>";
print_r($arrGetChartData);
exit();
Here i am getting this error Call to a member function fetch_array() on a non-object on line next to while condition line. I tried googling it and did not get result for my problem. Hope my question is clear. Thanks in Advance.
Always check for errors when running a query.
And please, don't stretch your code with unnecessarily long variables
$arrChartData[] = array();
$sql = "SELECT date, ratepersqft, location FROM ratepersqft WHERE project_id = 1";
$res = $mysqli->query($sql) or trigger_error($mysqli->error."[$sql]");
while($row = $res->fetch_assoc()) {
$arrChartData[] = $row;
}
Look, first variable contains just SQL code with no special meaning in your program, and it will be disposed on the very next line.
Second variable contains mysqli result. With no special meaning again. It's ok to use conventional name.
Same goes for the temporary $row
variable.
The only variable that have special meaning in your code is $arrChartData[]
- so, give it meaningful name. You need to initialize it before filling though.
And note the trigger_error
part which will convert mysqli error into PHP error. Always run your queries this way, to be notified of all mysql errors
By the way, it is good practice to get rid of all temporary variables, by moving them into some sort of helper function, making your application code as simple as following 2 lines
$sql = "SELECT date, ratepersqft, location FROM ratepersqft WHERE project_id = 1";
$arrChartData[] = dbGetAll($sql);
It will make your code shorter and more readable.
The query probably failed and mysqli::query
returned FALSE. Therefore $runGetChartData
is not a mysqli_result
object, but a boolean
, which is why you are getting your error.
From the documentation:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.