I am trying to save a result of SQL query into an associative array in PHP.
$result = $conn->query("SELECT `id`, `age` FROM `emp`"); while($row = $result->fetch_assoc()) { $rows[]=$row; }
But this is creating an associative array inside another array! How can I fix this?
Advertisement
Answer
You are querying all data from `emp`
table and creating new array form the result inside while
loop. You can print $rows
outside while loop using foreach
or for
loop or print inside while
loop without creating new $rows
array. If you are accepting one result form that query please use where clause to specify your desire row and make limit 1
. And Do not use while
loop
// outside while loop foreach($rows as $row) { print_r($row); }
or
$result = $conn->query("SELECT `id`, `age` FROM `emp` WHERE `id`=1 LIMIT 1"); $row = $result->fetch_assoc()