-2

Looking on how to remove array

My PHP Code :

<?php
header('Access-Control-Allow-Origin: *');

include('./db_connect.php');

if( isset($_GET["id"])) {
    $sql = "SELECT * FROM userstatus WHERE user_statusID = '".$_GET["id"]."'";
}

$result = $conn->query($sql);
$arr_data = array();
if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    array_push($arr_data,$row);
  }
}
else {
  $arr_data = null;
}
echo json_encode($arr_data);
$conn->close();

and result is :

[{"user_statusID":"1","status":"Admin"}]

i need to remove

"["{"user_statusID":"1","status":"Admin"}"]"

When Single row result is :

how I can do that

MMMMMMM
  • 67
  • 4

1 Answers1

0

You should avoid changing the API to sometimes return an array and sometimes not, else you would need to do some check in the consumer/client-side which checks if is array of objects or just a single object which could get messy.

Though to answer you can fetch_all rows, then do a simple if check to see if its only one row, if it is, then apply that single row back to $arr_data.

$arr_data = [];
if ($result->num_rows > 0) {
  $arr_data = $result->fetch_all(MYSQLI_ASSOC);
  if (count($arr_data) === 1) $arr_data = $arr_data[0];
}

Also, avoid using null as a response as again within the consumer of this script it would need to check if its null, not an array or a single object, (3 checks because is not a normalised response).


Obligatory note: You should fix the sql injection, see this: How can I prevent SQL injection in PHP?


Note, this answers the original question, my answer doesn't address the new bug introduced where $sql is undefined and no query is supplied.

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106