-1

I have tried this code but receiving error.

$queryfetch = 'select * from table';
    
$result = mysqli_query($connection, $queryfetch);
        
$row = mysqli_fetch_assoc($result);
        
$data = [];
foreach($row as $key) {
   $data[] = [
       'first_name' => $key['first_name'],
       'last_name' => $key['last_name']
    ];
}
        
echo json_encode($data);

How can I json encode specific keys using php ?

  • What is the error message? A specific key-value pair wouldn't be valid JSON. – Teemu Apr 10 '21 at 09:15
  • Warning: Illegal string offset 'first_name' – Dhaval Makwana Apr 10 '21 at 09:21
  • 1
    `$row = mysqli_fetch_assoc($result);` get's one single record. Your foreach will then iterate through all items in that record, which means that `$key` will contain the _value_ of `first_name`, 'last_name' etc on different iterations and not the complete row. – M. Eriksson Apr 10 '21 at 09:29
  • @MagnusEriksson is right, though if you only want the two columns, then don't use `*` in the query, then you can just fetch all – Lawrence Cherone Apr 10 '21 at 11:18
  • @MagnusEriksson, LawrenceCherone I have got the solution, instead of use foreach, I have directly use associative array result, see my answer below – Dhaval Makwana Apr 10 '21 at 15:55

1 Answers1

0

I have solved..

$queryfetch = 'select * from table';
    
$result = mysqli_query($connection, $queryfetch);
        
$row = mysqli_fetch_assoc($result);

$data[] = array(
    'first_name' => $row['first_name'],
    'last_name' => $row['last_name']
);

echo json_encode($data);

This code is working very well..