To store each result row in a variable, simply create one array
and add lines to it:
$variavel = array();
while ($linha = mysql_fetch_assoc($resultado))
$variavel[] = $linha;
This way, all values returned by the query will be stored in $variavel
, which may be used in the manner that it deems best.
Putting Values into Completely Different Variables
With the exception of some very specific cases, since I only think about the development of Frameworks with dynamic loading of modules or classes, or something of the kind, I see no advantage in doing this, being a gambiarra in the other uses.
But here it comes.
You can construct the name of a variable in a string, and then reference the variable with this name by duplicating the operator $
. Under the table, what PHP does is simply replace the variable of the string type with its content, and then reference the new variable name. This procedure can be performed several times, including.
Implementation:
$contador = 0;
while ($linha = mysql_fetch_assoc($resultado)) {
$nome = "variavel" . $contador++; // criamos o nome da variável.
$$nome = $linha; // criamos a variável propriamente dita.
}
// deste momento em diante, podemos referenciar diretamente as variáveis. Mas devemos tomar cuidado para saber QUAIS variáveis estão definidas e não.
// assumindo que pelo menos 3 linhas foram buscadas no banco de dados, o seguinte código é válido:
echo $variavel0 . "<br>";
echo $variavel1 . "<br>";
echo $variavel2 . "<br>";
Considering the previous example, and the implementation with array
, see how the implementation with array
is simpler and gives the same result in the case of printing the values returned to the database:
Array
foreach ( $variavel as $v )
echo $v . "<br>";
Independent Variables
$contador = 0;
while ( true ) {
$nome = "variavel" . $contador++;
if ( !isset($$nome) ) {
break;
}
echo $$nome . "<br>";
}
Observing
For the answer, I executed the following code using php -f
:
<?php
$linha = array("bla", "blabla", "blablabla");
$contador = 0;
foreach ( $linha as $v ) {
$nome = "variavel" . $contador++;
$$nome = $v;
}
echo $variavel0 . "\n";
echo $variavel1 . "\n";
echo $variavel2 . "\n";
The exit was:
bla
blabla
blablabla
Output in execution matches expected.
Remember which mysql_* functions are obsolete. Use mysqli_* or PDO.
– Marcos Xavier