Mysql returns only the first record

1

I created this function, but, it returns only the first record of the table.

function pega_conteudo_pela_id($id_assunto){

    global $conexao;

    $query3 = "SELECT * FROM '{$id_assunto}'";

    $result3 = mysqli_query($conexao,$query3) or die("MySQL error: " . mysqli_error($conexao) . "<hr>\nQuery: $query3");  

    while ($leiDB = mysqli_fetch_array($result3)) {
        return utf8_encode($leiDB['conteudo']. "<br/>");
    }
}

But if I put it on the links page, it works and takes all the records

    case 'codigo-civil':

        $query3 = "SELECT * FROM 'codigo-civil'";

        $result3 = mysqli_query($conexao,$query3);

        while ($leiDB = mysqli_fetch_array($result3)) {
            echo utf8_encode($leiDB['conteudo']. "<br/>");
        }

        break;
    
asked by anonymous 20.05.2015 / 06:07

2 answers

2

You are using return within the pega_conteudo_pela_id function, but in practice it seems to me that this function does not have to return anything because in the other example you are doing echo of what you need. The return stops the function. Remove return and put echo , or if you want the function to return the contents of this query you can do this:

echo pega_conteudo_pela_id($variavel);

and within the function:

$results = '';
while ($leiDB = mysqli_fetch_array($result3)) {
    $results.= utf8_encode($leiDB['conteudo']. "<br/>");
}
return $results;

A semantic note: when you call the pega_conteudo_pela_id function, it gives me the idea that you want to fetch data by the ID of a DB column. But in your example the parameter $id_assunto of the function is used to select a column. I would change those names so as not to fool about the functionality they comply with.

    
20.05.2015 / 06:13
1

The "return" command interrupts the execution loop in the first loop, so it is returning only the first record it encounters.

Change% of% by% of% and see the difference

return utf8_encode($leiDB['conteudo']. "<br/>");

Switch to echo

echo utf8_encode($leiDB['conteudo']. "<br/>");

obs: I will comment on the code, good programming practices, etc. But I think it's worth pointing out that the code is very poorly written. Look for good programming practices.

    
20.05.2015 / 06:16