how can I send multiple data from mysql to a php array and echo the first two entries? In my database I have the columns name, xkoord, ykoord. I have tried with json, but I guess this doesn't work. What I have is the following:
function load_db($var, $xkoord, $ykoord){
global $db;
$result = mysqli_query($db,"SELECT $var FROM armydb WHERE xkoord = '$xkoord' AND ykoord = '$ykoord'") OR DIE ('Fehler!');
$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json );
}
I call this function this way:
<?php
$name_array = json_decode(load_db('name', 1, 0), true);
echo $name_array[0];
echo $name_array[1];
?>
This doesnt work. Any Suggestion?
try
function load_db($var, $xkoord, $ykoord){
global $db;
$result = mysqli_query($db,"SELECT $var FROM armydb WHERE xkoord = '$xkoord' AND ykoord = '$ykoord'") OR DIE ('Fehler!');
$resultset = mysqli_fetch_all ($result, MYSQLI_ASSOC);
return $resultset;
}
print_r(load_db('name', 1, 0));
you don't have to encode the result to json since you can just return
the data and pass it between functions etc.
You need to use return
, not echo
:
return json_encode($json);
echo
just prints its argument, it doesn't return it to the caller of the function.
Also, $name_array
will be a 2-dimensional array: the first dimension is the rows of the results, the second dimension is an associative array of the columns. So $array[0]
is an array, you can't usefully echo that. You should do:
echo $name_array[0]['name'];
echo $name_array[1]['name'];
Why are you using json_encode()
in the first place? Why not just return the array?
Lets make it easier
<?php
$query = mysql_query("select * from armydb where xkoords = '$xcords' and ycords = '$cords'");
// now if you need 1 row;
$row = mysql_fetch_assoc($query);
echo $row['name'];
// if u need more then one
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'];
}
?>