-3

I'm trying to figure out how to save SQL query results into array:

This loop only produces 1 result in array:

<?php

$term = $_GET['term'];


$query = "SELECT * FROM Bob WHERE h_city LIKE '%".$term."%' ORDER BY 
h_city ASC";
$result = mysqli_query($conn, $query);

   while($row = mysqli_fetch_assoc($result)) {
        $result = $row['h_city'];
        array_push($result);
    }
    $json = json_encode(array($result));
    echo $json;
    ?>

result is: ["example1"] How to save query into array like ["example1","example2"]. Any thoughts what I might be doing wrong, or anyone can point me to the right direction?

EDIT as it was mentioned in the comments this way of doing queries is prone to SQL injections: more info here more info on converting results to arrays: more info here

5
  • 3
    Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Commented Sep 16, 2020 at 12:22
  • 2
    array_push($result); makes little sense. You need to supply at least two parameters, starting with the second one, those are the values you actually want to push into the array. Commented Sep 16, 2020 at 12:24
  • 2
    $result is your query result then on first loop iteration you destroy it $result = $row['h_city']; Commented Sep 16, 2020 at 12:25
  • $result is already being used as the resource for your query, and you're overwriting $result. The array push is just wrong here. Commented Sep 16, 2020 at 12:25
  • 3
    Please go and enable proper PHP error reporting, NOW! PHP would have already told you about this (“Warning: array_push() expects at least 2 parameters, 1 given in […]”). It should really not be necssary that we alert you to this kind of mistake/inattention, when PHP by itself can do that already. Commented Sep 16, 2020 at 12:25

1 Answer 1

3

I think a simple code change will do you well here, just put all of the row info in an array called items (or any other name that makes sense).

while($row = mysqli_fetch_assoc($result)) {
    $items[] = $row['h_city']; // add to an array called items
}
$json = json_encode($items);
echo $json;

I think likely your query is wrong too because you are limiting the list of cities here:

WHERE h_city LIKE '%".$term."%'

Which should only return a match for a single city.

WARNING You should listen to those who provided a critique of your code in the comments under your question. You made a lot of fundamental mistakes that you could likely have solved yourself if you had error reporting on and visible.

Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.