Pass results from an array to variables

Asked

Viewed 1,114 times

2

The query below returns the total number of records by mode:

 $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>';  

She returns to me like this:

15
10
20

How to pass each result line to a variable?

  • Remember which mysql_* functions are obsolete. Use mysqli_* or PDO.

1 answer

5


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.

  • I need each row in a different variable type $variable1[] = $line; $variavel2[] = $line;

  • 1

    Is it possible to do that? Yes. But you need to have an excellent reason to do it instead of using one array, for what you do with it is nothing more than gambiarrar a array. I’ll update my answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.