Use mysqli_fetch_all in procedural mode

Asked

Viewed 87 times

0

I need to bring results from a database that stays that way:

Fernando Pessoa, Pablo Neruda, Manuel Bandeira

For that, I’m trying this way:

$sql = mysqli_query(...);
$mostrar = mysqli_fetch_all(MYSQLI_ASSOC);
echo join(",",$mostrar["Nome"]);

But it brings no return, nor with var_dump(). I see you’ve got that post, but I couldn’t understand very well how it works. How can I use in procedural mode?

When I use it that way:

while($cs = mysqli_fetch_array($sql))
{
  echo $cs["Nome"];
}

Works normally!

2 answers

3


In procedural mode, the first parameter must be the result of mysqli_query

Wrong: mysqli_fetch_all(MYSQLI_ASSOC)

Correct: mysqli_fetch_all($sql, MYSQLI_ASSOC)

As you said it works locally but not on the server, so probably missing install the extension Mysql Native Driver on your server, you can use this function that receives a statement

function fetch($statement)
{
    $metadata = $statement->result_metadata();

    $columnName = array();

    foreach ($metadata->fetch_fields() as $field) {
        $columnName[] = json_decode(json_encode($field), true)['name'];
    }

    $metadata->free_result();

    $columnValue = $columnName;

    if (!$statement->bind_result(...$columnValue)) {
        return null;
    }

    $data = array();

    while($statement->fetch()) {
        $row = array();

        for ($i = 0; $i < count($columnName); $i++) { 
            $row[$columnName[$i]] = $columnValue[$i];
        }

        $data[] = $row;
    }

    return $data;
}
  • Hello William. Try this way, but it didn’t work either.

  • Show an error? Is the SQL query correct? If it is not $sql may be a boolean and not work

  • No error and the query is right. I changed my post and includes it with while() which normally returns the results.

  • Guilherme, your solution works on my site, but not on the remote server. I believe it is some configuration there. I put an alternative solution and I thank you for your help.

  • I updated the answer

1

Unfortunately I believe that the problem is some configuration of the server, since Guilherme’s solution works on my site. To solve this, I created an alternative solution in the query itself in case someone goes through the same problem as me, thus staying:

$sql = mysqli_query($this->conexao,"SELECT *,GROUP_CONCAT( Nomes ORDER BY Nomes ASC SEPARATOR ', ' ) AS NomesUsuarios FROM tabela;");
$cs = mysqli_fetch_object($sql);
echo $cs->NomesUsuarios;

Browser other questions tagged

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