Store all query data in an array.
$array = array();
while($row = $result->fetch_assoc()) {
$array[] = $row;
}
//exemplo retornado
//Array ( [0] => Array ( [lamp_estado] => estado AAA [lamp_descricao] => lâmpadas LED ) [1] => Array ( [lamp_estado] =>estado BBB [lamp_descricao] => lâmpadas fluorescentes ) [2] => Array ( [lamp_estado] => estado CCC [lamp_descricao] => lâmpadas tubulares ) .....
And to access the array elements:
$estado = $estado2 = $array[1]['lamp_estado'];
echo $estado; //estado BBB
echo $estado2; //estado BBB
$descricao = $descricao2 = $array[1]['lamp_descricao];
echo $descricao; //lâmpadas fluorescentes
echo $descricao2; //lâmpadas fluorescentes
Clarifying this problem of ta gravando apenas o último valor da busca
Imagine a table whose column is called "lamps" and the arrow (->) is the pointer of the list.
-> lâmpadas LED
lâmpadas fluorescentes
lâmpadas tubulares
When we use the function $result->fetch_assoc()
, it returns the first line:
while($row = $result->fetch_assoc()) {
$estado=$row["lamp_estado"];
At this time the variable $state takes on the value LED lamps and the pointer moves one position forward, and our list is as follows:
lâmpadas LED
-> lâmpadas fluorescentes
lâmpadas tubulares
At this time the variable $state takes on the value fluorescent lamps and the pointer moves one position forward, and so on.
So that’s why in your while in the variable $estado
, as well as the other variables, only the last name appears.
When executing the while
the value of the variable $estado
is being overwritten because you are not concatenating the values.
You can for example do so to concatenate
$estado = $estado.",".$row["lamp_estado"];
which would result in a string with data separated by comma.
The way you’re doing with
$estado=$row["lamp_estado"];
always replace the previous one, just as you are reading the 2 fields coming from the table twice. How you intended to use the result ?– Isac
Hello Joao Claudio, don’t forget to mark the answer that solved your problem as accepted, see how and why this is important in this post https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
– user60252
I will use 10 variables, to create 10 buttons each button will turn a light bulb using bd to have control of them. I need to know what state they’re in, so I needed this command. ^^
– Joao Claudio