Search code examples
phpjqueryjsonstringify

JSON object output not right


I retrieve JSON from php:

<?php
 require("includes/connection.php");

//$queryString = "home";
$returnArray = array(); 

if (!$server) 
{ 
    die('Connect Error (' . mysqli_connect_errno() . ')' . mysqli_connect_error() );  
} 


$query =    "SELECT * 
            FROM stuff
            WHERE name LIKE '%" . $queryString . "%' 
            ORDER BY name LIMIT 1";

if($result = $server->query($query))
{
    while ($row = $result->fetch_assoc())
    {
        array_push($returnArray, $row);
        
    }


}           
   
echo json_encode($returnArray);

?>

And javascript:

var home = "home";
  $.getJSON("db/getJSON.php", {queryString: ""+home+""},
    
function(data){
            
    jsn = JSON.stringify(data);
    $("#outputtester").html(jsn);
        consoleOut("JSON: "+jsn);

   });

It outputs quite a nice string:

[{"UID":"1","IDS":"1,2,3","name":"home","type":"thing","cat_id":"home"}]

But I think the two [] are not supposed to be there, because it is not an array of arrays?

I tried putting echo "Things: ". before the json_encode, so I could identify the array of arrays. But it wont work

I tried to access 'data' without stringifying, as an object, it should work with something like:

data.UID

or

data.name

but I get an object Object output each time, also when I stringify them..

Any idea what I'm doing wrong?

Can't find a whole bunch of info on working with JSON arrays from, all the stuff I find manually make the JSON in javascript code..


Solution

  • Remove the while loop

    <?php
     require("includes/connection.php");
    
    $row = array(); 
    
    if (!$server) 
    { 
        die('Connect Error (' . mysqli_connect_errno() . ')' . mysqli_connect_error() );  
    } 
    
    
    $query =    "SELECT * 
                FROM stuff
                WHERE name LIKE '%" . $queryString . "%' 
                ORDER BY name LIMIT 1";
        
        if ($result = $server->query($query)) {
            $row = $result->fetch_assoc(); // Fetch a single row
            
        }
        
        echo json_encode($row);
    

    You can also modify your query to prevent sql injections

    $query = "SELECT * 
              FROM stuff
              WHERE name LIKE ? 
              ORDER BY name LIMIT 1";
    
    if ($stmt = $server->prepare($query)) {
        // Bind the parameter to the query
        $searchParam = "%" . $queryString . "%"; // Add wildcards for the LIKE clause
        $stmt->bind_param("s", $searchParam); // 's' denotes a string parameter
    
        // Execute the prepared statement
        $stmt->execute();
    
        // Get the result
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
           // Close the statement
        $stmt->close();
    }