0

I want to build an array in PHP from SQL query and send it back via ajax to my JS file.

$id = clear(filter_input(INPUT_POST, 'id')); 
$sql = 'SELECT * FROM `counties` WHERE `id`="'.$id.'"';
$query = mysqli_query($con, $sql);
$array = array();
while($result = mysqli_fetch_array($query)) {
    $id = $result['id'];
    $name = $result['name'];
    $array[] = array('id' => $id, 'name' => $name);
}

echo json_encode($array);

This is my code. In response I have always just one element. There's a lot of more. How could i do that correctly? I was browsing whole Internet and I didn't find anything useful... :(

  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Apr 26 '17 at 20:56
  • It looks like you're only selecting one record, given you're matching one id. – Jay Blanchard Apr 26 '17 at 20:57
  • Where id =id. How many records did you expect to receive – Rotimi Apr 26 '17 at 20:58
  • @JayBlanchard has right. I was selecting just one record. But guys Little Bobby says this code is at risk for SQL Injection. What am I doing wrong? –  Apr 26 '17 at 20:59
  • Read the link in my comment for what you're doing wrong where SQL Injection is concerned. – Jay Blanchard Apr 26 '17 at 21:00

1 Answers1

0
$id = $_POST['id']; 
$query = mysqli_query($con, "SELECT id,name FROM `counties` WHERE `id`='$id'");
$array = mysqli_fetch_all($query,MYSQLI_ASSOC);
echo json_encode($array);

this may simplified code