Passing results from an array to variables

2

The query below returns the total number of records per modality:

 $sql = "SELECT modalidade, COUNT(*) as total FROM a_finan GROUP BY modalidade";
 $resultado = mysql_query($sql) or die( mysql_error()); 
 while ($linha = mysql_fetch_assoc($resultado)) 

 echo   $linha["total"] . '<br>';  

It returns me like this:

  

15
  10
  20

How to pass each result line to a variable?

    
asked by anonymous 17.04.2015 / 15:02

1 answer

5

To store each result row in a variable, just create a array and add the lines in it:

$variavel = array();
while ($linha = mysql_fetch_assoc($resultado))
    $variavel[] = $linha;

In this way, all values returned by the query will be stored in $variavel , which can be used in any way you like.

Placing Values in Completely Different Variables

With the exception of some very specific cases, which only comes to mind the development of Frameworks with dynamic loading of modules or classes, or something, I see no advantage in doing so, if it is a game in the other uses.

But there you go.

You can construct the name of a variable in a string, and then reference the variable with this name by duplicating the $ operator. Underneath the cloth, what PHP does is simply replace the string variable with its contents, and then reference the new variable name. This procedure can be performed several times, inclusive.

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 case of printing the values returned to the bank:

Array

foreach ( $variavel as $v )
    echo $v . "<br>";

Independent Variables

$contador = 0;
while ( true ) {
    $nome = "variavel" . $contador++;
    if ( !isset($$nome) ) {
        break;
    }
    echo $$nome . "<br>";
}

Note

For the answer, I ran 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 output was:

bla
blabla
blablabla

The output in execution is as expected.

    
17.04.2015 / 15:09