-4

I have my response where I want to fill below.

$response = array(
  "year" => array(),
  "playerName" => array(),
  "cardVariation" => array()
);

I have a simple query to my table.

$sql = "SELECT * from $TBL";
$result = $conn->query($sql);

I will then lop through my results.

while($row = $result->fetch_assoc()) {
  $year = $row['year'];
  $playerName = $row['name'];
  $cardVariation = $row['cardV'];

  // add to response
  $response['year'] = $year;
  $response['name'] = $playerName;
  $response['cardV'] = $cardVariation;

}

echo json_encode($response);

Expected response:

{"year": ["1999", "2000"], "name": ["bill", "jess"], "cardV": ["base","silver"]}

Only the last one gets added. I couldn't find an "append" method for PHP, unless i looked over it.

letsCode
  • 2,774
  • 1
  • 13
  • 37
  • 2
    `$response['year'][] = $year;` should do the trick – 0stone0 Sep 03 '20 at 15:12
  • Does this answer your question? [How to add elements to an empty array in PHP?](https://stackoverflow.com/questions/676677/how-to-add-elements-to-an-empty-array-in-php) – 0stone0 Sep 03 '20 at 15:13
  • 2
    Only tangentially related, but it appears you're concatenating a PHP variable directly into SQL query string. This is likely introducing a critical [SQL injection vulnerability](https://stackoverflow.com/questions/601300/what-is-sql-injection) into your script. You should strongly consider using [prepared statements and parameterized queries](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) to mitigate this. – esqew Sep 03 '20 at 15:14

2 Answers2

1

You are over writing the values each time round the loop so place the values into a new occurance each time by using $response['year'][] = . Also you are wasting time moving values into scalar variables.

while($row = $result->fetch_assoc()) {
  // add to response
  $response['year'][] = $row['year'];
  $response['name'][] = $row['name'];
  $response['cardV'][] = $row['cardV'];

}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

You can use array_push() or just

$response['year'][] = $year;
$response['name'][] = $playerName;
$response['cardV'][] = $cardVariation;

https://www.php.net/manual/de/function.array-push.php

Chaz
  • 672
  • 1
  • 5
  • 19