2

I have a table (see image below) that includes the polish and latin names for a selection of different herbs.

I'd like to obtain a $herbs[] array, that contains an array for each row, e.g.:

$herbs = [[mieta pieprzowa, mentha piperita],[kozlek lekarski, valeriana medicinalis]...]

The code for receiving latin_name looks like this, so what should I change?

<?php
$connection = new mysqli("127.0.0.1","root","password","herbarium");
if ($connection→connect_error) die("Fatal Error");
$herb = $_GET['q'];
$query = "SELECT * FROM herbs WHERE (latin_name LIKE '%$herb%') OR (polish_name LIKE '%$herb%')";
$result = $connection→query($query);
$data = array();
while ($row=$result→fetch_assoc()){
$data[] = $row['latin_name'];
}
echo json_encode($data);
?>

my table

DaveyDaveDave
  • 9,821
  • 11
  • 64
  • 77
  • 1
    What the error? Also, think about SQL Injection: https://stackoverflow.com/questions/47837400/sql-injection-mysql – Adam Aug 28 '18 at 14:18
  • You want to get the entire row? so why don't you just remove `['latin_name']` from this line: `$data[] = $row['latin_name'];` ? – dWinder Aug 28 '18 at 14:19
  • Instead of latin_name I'd like to get also polish_name so it would as in example –  Aug 28 '18 at 14:20

1 Answers1

1

I believe you're looking for mysqli_fetch_all() + a small change of your SQL Query.

In example below I changed your query to fetch only two columns (latin and polish name) and instead of using while() loop you can fetch all records at once (until you don't need to process this data).

$connection = new mysqli("127.0.0.1","root","password","herbarium");
if ($connection→connect_error) die("Fatal Error");
$herb = $_GET['q'];
$query = "SELECT latin_name, polish_name FROM herbs WHERE (latin_name LIKE '%$herb%') OR (polish_name LIKE '%$herb%')";
$result = $connection→query($query);
$data = mysqli_fetch_all($result);
echo json_encode($data);

It should return you an array with key=>value result like:

[
  [
    'latin_name' => 'Abc',
    'polish_name' => 'Abc_PL'
  ],
  // ...
]

Which might be a bit better idea instead of returning only values.

Tomasz
  • 4,847
  • 2
  • 32
  • 41
  • 1
    Thanks :> Much greater and understandable for me! –  Aug 28 '18 at 14:31
  • 1
    @farmaceut Powodzenia! ;) – Tomasz Aug 28 '18 at 14:36
  • 1
    Dzięki, dzięki ;) Pojawię się tu nie raz jeszcze –  Aug 28 '18 at 14:40
  • To może jeszcze w ramach tego dopytam sie... Jakkolwiek zwraca mi też wartość z polish_name, to niestety nie ma ogonków, a baza danych jest w utf-8... co poradzic na to? –  Aug 28 '18 at 15:29
  • Sprawdz http://php.net/manual/de/mysqli.set-charset.php i czy plik .php ma kodowanie utf8 – Tomasz Aug 29 '18 at 11:48