Returning Multiple Rows with MySqli and Arrays

后端 未结 3 1404
太阳男子
太阳男子 2020-11-30 13:20

For the past two days or so I\'ve been converting my functions to mysqli. I\'ve run into a problem. I have a function that returns an array containing a row from the databas

相关标签:
3条回答
  • 2020-11-30 13:39

    You have to use a loop to get them all at once:

    <?php
    function resultToArray($result) {
        $rows = array();
        while($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
        return $rows;
    }
    
    // Usage
    $query = 'SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4';
    $result = $mysqli->query($query);
    $rows = resultToArray($result);
    var_dump($rows); // Array of rows
    $result->free();
    
    0 讨论(0)
  • 2020-11-30 13:39

    I'm late, but I believe this is what you wanted to achieve:

    $mysqli = new mysqli("localhost", "user", "password", "database");
    $fields = "`primary_id`, `poster_id`, `profile_user_id`, `post`";
    
    function display_posts () {
    
        global $mysqli;
        global $fields;
    
        $query = "SELECT DISTINCT $fields FROM `posts` WHERE `profile_user_id` = $user_id LIMIT 4";
    
        $posts = $mysqli -> query($query) or die('Error: '.$mysqli -> error);
    
        if ($posts -> num_rows > 0) {
    
            while ($row = $posts -> fetch_assoc()) {
    
            $value = $row['/*The table column here (You can repeat this line with a different variable e.g. $value 2, $value 3 etc and matching them with the respective table column)*/'];
    
            echo $value./*Concatenate the other variables ($value 1 etc) here*/'<br />';
    
            }
    
        }else {
    
            echo 'No records found.';
    
        }
    
    }
    
    //Call the function
    display_posts ();
    
    0 讨论(0)
  • 2020-11-30 13:41

    Why not use directly like this:

    $result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);
    
    0 讨论(0)
提交回复
热议问题