How do I return all rows from the SQL query with PHP?

0

The result I have from the SQL query is this:

I want to return these two rows from column 'publication'. 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 index 1 of '$ tweets', the error is this: 'Undefined offset: 1 in'. Or is it just returning the first line of the query and I want it to be returned all, how do I?

    
asked by anonymous 23.05.2018 / 13:10

1 answer

1

It's important to understand how each function works. The mysqli_fetch_row function, as the manual tells you:

  

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.

Your query being just one column, the result should be similar to this:

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

That's why accessing index 1 causes an error. It does not exist, therefore, there is only one column as a result of the query.

Also, 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 array offset   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 rows. So you can use while to return all results:

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

And, in this way, you will iterate on all query results.

Another way is to use the mysqli_fetch_all function. Unlike mysqli_fetch_row , it will return an array with all results from the database. data:

$resultArray = mysqli_fetch_all($buscaTweets);

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