PHP mySQLi_fetch_all: iterate through each row

前端 未结 4 515
梦毁少年i
梦毁少年i 2020-12-20 08:19

I am retrieving the rows of my query as such:

$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);

How can I do:

(PSEUDO CODE)
         


        
相关标签:
4条回答
  • 2020-12-20 08:41

    I would use something like this:

    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        echo $row['name_of_your_column'];
    }
    

    where result is:

    $result = mysqli_query($connection, $query);
    
    0 讨论(0)
  • 2020-12-20 08:45
    $rows = mysqli_fetch_assoc($result, MYSQLI_ASSOC);
    

    Use the mysqli_fetch_assoc function.

    And the use the foreach as:

    foreach($rows as $column => $value) {
      echo $column." = ".$value;
    }
    

    Note: You can also use foreach with mysqli_fetch_all.

    0 讨论(0)
  • 2020-12-20 08:58

    I have written a small code, hope it solves the query.

        //Query to be executed;
    $qry="select * from `tableName`";
    //Performs a query on the database;
    //here conn is a link identifier returned by mysqli_connect or mysqli_init function;
    $result=mysqli_query($conn,$qry);
    //Gets the number of rows in a result;
    $rowcount=mysqli_num_rows($result);
    //Fetches all result rows as an associative array;
    $row = mysqli_fetch_all($result,MYSQLI_ASSOC);
    //Iterating each row;
    for($i=0;$i<$rowcount;$i++)
    {
        echo "<br> ".$row[$i]['`column_name_1`']." ".$row[$i]['`column_name_2`']." ".$row[$i]['`column_name_3`'];
    }
    

    Example Database Table Mysql Table snapshot Code

    //here conn is a link identifier returned by mysqli_connect or mysqli_init function;
    $conn = mysqli_connect("localhost","root","","nsgdb") or die('Error connecting to MySQL server.');
    //Query to be executed;
    $qry="select * from users";
    //Performs a query on the database;
    $result=mysqli_query($conn,$qry);
    //Gets the number of rows in a result;
    $rowcount=mysqli_num_rows($result);
    //Fetches all result rows as an associative array;
    $row = mysqli_fetch_all($result,MYSQLI_ASSOC);
    //Iterating each row;
    for($i=0;$i<$rowcount;$i++)
    {
       echo "<br> ".$row[$i]['id']." ".$row[$i]['user']." ".$row[$i]['pass'];
    }
    

    Output of the code

    0 讨论(0)
  • 2020-12-20 09:04

    You pseudo code is all fine.. you just need to turn it into PHP....

    Answer to first question:

    // Loop through each row and print it
    foreach( $rows as $row ):
       print_r( $row )
    endforeach;
    

    Second question.. something like:

    foreach( $rows as $row ):
       foreach( $row as $col ):
          echo $col;
       endforeach;    
    endforeach;
    
    0 讨论(0)
提交回复
热议问题