-2

this is my php script

$con = mysqli_connect(HOST,USER,PASS,DB);

if($_SERVER['REQUEST_METHOD']=='GET') 
{

$qry_check="SELECT * FROM `tb_user`";

$stmt = $con->prepare($qry_check);

if ($stmt->execute()){

     echo "Success";

}}

else 
     echo "Fail";

}
?>

when i run this query on my mysqli online server i get result which i have attached below i need this result as a json array when i call this json url, hanks in advance,enter image description here

enter image description here

spinsch
  • 1,299
  • 10
  • 23

2 Answers2

0

try this

<?php

    $con = mysqli_connect(HOST,USER,PASS,DB);

    if($_SERVER['REQUEST_METHOD']=='GET') 
    {
        $stmt = $con->prepare("SELECT * FROM tb_user");

             if ($stmt->execute()) {
                    $users = array();
                    $user=$stmt->get_result();
                     while($row = $user->fetch_assoc()){
                        $users[]=$row;
                     }

                     $stmt->close();                       

                echo json_encode($users);
            }
}

?>

or use this code. Add your remaining columns in this code for full result

    <?php

    $con = mysqli_connect(HOST,USER,PASS,DB);

    if($_SERVER['REQUEST_METHOD']=='GET') 
    {
        $stmt = $con->prepare("SELECT user_id, category_id FROM tb_user");

             if ($stmt->execute()) {
                    $users = array();
                    $stmt->bind_result($user_id, $category_id);
                      while ($stmt->fetch()) {

                         $user["user_id"] = $user_id;
                        $user["category_id"] = $category_id;
                        $users[] = $user;
                     }

                     $stmt->close();                       

                echo json_encode($users);
            }
}

?>
Vinayak B
  • 3,922
  • 2
  • 21
  • 49
0

I already mention in comment that mysqli != PDO. But I thnk you don't get it.

You are initializing connection with mysqli then doing all process with PDO so you don't get result

<?php  

    $servername = HOST;
    $username = USER;
    $password = PASS;
    $dbname = DB;
    $con = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

    if($_SERVER['REQUEST_METHOD']=='GET') 
    {
        $stmt = $con->prepare("SELECT * FROM tb_user");

             if ($stmt->execute()) 
             {
                    $users = array();                        
                     while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
                        $users[]=$row;
                     }

                     $stmt->close();                       

                echo json_encode($users);
            }
}

?>
B. Desai
  • 16,092
  • 5
  • 22
  • 43