How do you return all the rows of the SQL query with PHP?

Asked

Viewed 346 times

0

The result I have of the SQL query is this:
inserir a descrição da imagem aqui

I want to return these two lines of the 'publishing' column. But using this code:

<?php  
  //Código para buscar os tweets do usuário
  $sqlTweets = "SELECT publicacao FROM tweets INNER JOIN usuarios ON  usuarios.id_usuario = tweets.id_usuario WHERE apelido_usuario = '{$usuario}' OR email = '{$usuario}'";
  $buscaTweets = mysqli_query( $link, $sqlTweets );

  if ( $buscaTweets ) {
    $tweets = mysqli_fetch_row( $buscaTweets );
  }
?>

An error is returned when I try to access the index 1 of '$tweets', the error is this: 'Undefined offset: 1 in'. That is just returning me the first line of the query and I want it to be returned all, as I do ?

1 answer

1


It is important to understand the functioning of each function. The function mysqli_fetch_row, as the manual informs:

mysqli_result::fetch_row -- mysqli_fetch_row - Get a result Row as an enumerated array

Returns a result line (from the/query query) as an enumerated array.

Since your query is only one column, the result should be similar to this:

array(1) { [0]=> string(9) "teste_sql" }

That is why when accessing index 1 an error occurs. It does not exist, because there is only one spine as a result of the consultation.

Still, according to the manual:

Fetches one Row of data from the result set and Returns it as an enumerated array, Where each column is stored in an offset array Starting from 0 (zero). Each subsequent call to this Function will Return the next Row Within the result set, or NULL if there are no more Rows.

Each subsequent query will return the next result, or NULL if there are no more lines. So you can use while to return all results:

while($row = mysqli_fetch_row($buscaTweets))
{
    printf('Resultado: %s' , $row[0]);
}

And this way you will iterate on all results of the consultation.

Another way would be to use the function mysqli_fetch_all. Other than mysqli_fetch_row, it will return an array with all database results:

$resultArray = mysqli_fetch_all($buscaTweets);

foreach($resultArray as $row)
{
    printf('Resultado: %s' , $row[0]);
}

Browser other questions tagged

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