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

3
  • 1
    What the error? Also, think about SQL Injection: stackoverflow.com/questions/47837400/sql-injection-mysql Commented Aug 28, 2018 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']; ? Commented Aug 28, 2018 at 14:19
  • Instead of latin_name I'd like to get also polish_name so it would as in example Commented Aug 28, 2018 at 14:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks :> Much greater and understandable for me!
@farmaceut Powodzenia! ;)
Dzięki, dzięki ;) Pojawię się tu nie raz jeszcze
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?
Sprawdz php.net/manual/de/mysqli.set-charset.php i czy plik .php ma kodowanie utf8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.