-1

Maybe you can help me. DB connection is ok (Connected successfully), the table name is correct (course_details), but echo json_encode($data); is NULL

<?php

   include "db.php";

   // Check connection
   if ($con->connect_error) {
      die("Connection failed: " . $conn->connect_error);
   } 
   echo "Connected successfully";

   $data=array();
   $q=mysqli_query($con,"'SET CHARACTER SET utf8' select * from 'course_details'");
   while ($row=mysqli_fetch_object($q)){
      $data[]=$row;
   }


   echo json_encode($data); 
   $conn->close();
?>

Thanks in advance!

ArmKh
  • 435
  • 9
  • 31
mario
  • 3
  • 2
  • 1
    Add the output of `$data` – ArmKh Apr 05 '18 at 14:08
  • 5
    Your query is going to fail. You have two statements that aren't separated, and one is surrounded by single quotes but should not be. You can't run two statements in a query without using `mysqli_multi_query`. And tables need to be surrounded by backticks, not quotes. This is why `$data` is empty. – aynber Apr 05 '18 at 14:10

1 Answers1

-1

firstly I would suggest wrapping the query in a try catch block

secondly as is mentioned in the comments above you have 2 queries in in the string.

try{
    $q=mysqli_query($con,"select * from `course_details`");
    $data = [];
    while ($row=mysqli_fetch_object($q)){
        array_push($data, $row);
    }
    echo json_encode($data); 
} catch (Exception $e) {
    echo "It reached the catch block " . $e->getMessage();
}
Lonergan6275
  • 1,938
  • 6
  • 32
  • 63
  • Your query will still fail because of the single quotes around the table. And since it would return null instead of throwing an exception, the OP should check for [mysqli errors](http://php.net/manual/en/mysqli.error.php). – aynber Apr 05 '18 at 14:33
  • @aynber whats the problem with wrapping the table name in single quotes? – Lonergan6275 Apr 05 '18 at 14:34
  • 1
    It will be treated as a string instead of a table or column name. http://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks-in-mysql – aynber Apr 05 '18 at 14:35