I stored an array in the variable $stringPedidos. I'm trying to use this variable as an array in $resp but it's not working.
I'm trying to display a keyboard that contains the product names depending on a user order ID extracted from the db. The $stringPedidos variable contains the array needed for displaying the keyboard at a Telegram Bot using PHP. I want to use $stringPedidos as an array, the problem is that $stringPedidos is executed as a string.
$query = mysqli_query($conn, "SELECT * FROM pedidos WHERE usuario_id='".$id."'");
if(mysqli_num_rows($query) > 0){
$stringPedidos= "array(";
$query = "SELECT producto_id FROM pedidos WHERE usuario_id='".$id."'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$producto_id = $row['producto_id'];
$queryProductos = "SELECT name FROM productos WHERE id='".$producto_id."'";
$resultProductos = mysqli_query($conn, $queryProductos) or die(mysqli_error($conn));
while ($rowProductos = mysqli_fetch_array($resultProductos, MYSQLI_BOTH)) {
$productoName = $rowProductos["name"];
$stringPedidos .= 'array("'.$productoName.'"),';
}
}
$stringPedidos .= 'array("Return↩️")';
$stringPedidos .= ")";
$resp = array("keyboard" => eval($stringPedidos),"resize_keyboard" => true,"one_time_keyboard" => true,"remove_keyboard" => true);
}
Output: array(array("testProduct"),array("testProduct2"),array("Return↩️"))
The output is right, but it's not executed as an array, because it isn't working.
What you need to do is to add eval("\$newStringPedidos = $stringPedidos;");
before the last line. This will store your array in a new variable $newStringPedidos
. Now the variable $newStringPedidos
is really an array and not a string, so you can use it in the last line and it shall work.
eval("\$newStringPedidos = $stringPedidos;");
$resp = array("keyboard" => $newStringPedidos,"resize_keyboard" => true,"one_time_keyboard" => true,"remove_keyboard" => true);
The problem is that you are using the eval() function incorrectly. Visit https://www.w3schools.com/pHP/func_misc_eval.asp
Furthermore, it is usually much better to avoid eval() function, since it is quite confusing and in your case I think you really do not need it.