-1

This php connection code is throwing an error...

This is the full code:

<?php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("localhost", "myusername", "mypassword", "mydatabase");

$result = $conn->query("SELECT title FROM mytable");

var_dump($result);

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "") {$outp .= ",";}
    $outp .= '"title":"'. $rs["title"]     . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();

echo($outp);

?>

This is the error that it's throwing:

Fatal error: Call to a member function fetch_array() on a non-object in /home/mypath/public_html/connection.php on line 13

The error points here:

while($rs = $result->fetch_array(MYSQLI_ASSOC)) {

How can I fix this?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Satch3000
  • 47,356
  • 86
  • 216
  • 346

1 Answers1

2

Your query failed. mysqli::query returns false when the query fails, and a mysql_result object otherwise.

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.

Make sure your query is correct by running it on the console. You should also check for an error while running your query.

$result = $conn->query("...") or trigger_error($conn->error);
John Bupit
  • 10,406
  • 8
  • 39
  • 75