Ukor Ukor - 7 months ago 9
PHP Question

PHP function is not returning all the data in MySQL table

I have a function

function get_table_content(){
$sql = "SELECT * FROM my_table WHERE id > 0";
$result = $this->query($sql);
while ($row = $this->fetch($result)){
return ($row);
}
}


The problem is, when i call this function it only return the first entry in my database.
How can i make this work it suppose to return about all the data in the table.
I have also tried this and it is not working too

function get_table_content(){
global $database_connection;
$sql = "SELECT * FROM my_table WHERE id > 0";
$result = mysqli_query($database_connection, $sql);
while ($row = mysqli_fetch_assoc($result)){
return ($row);
}
}


I think the best way to go about this is to return an array and do my foreach operation on it but i can not get it to work.

Can someone help me out Please.
P.S i will preffer it to return an array of all the data in the data so i can do a foreach operation on it.
Thank you

Answer

The problem is, in the while loop after fetching one row from the result set you're returning the result from the function, and hence you're getting only the first row from the result set. Either use mysqli_fetch_all() function or an array in the while loop to store the result.

Method(1):

function get_table_content(){
    global $database_connection;
    $sql = "SELECT * FROM my_table WHERE id > 0";
    $result = mysqli_query($database_connection, $sql);

    return mysqli_fetch_all($result);
}

Method(2):

function get_table_content(){
    global $database_connection;
    $sql = "SELECT * FROM my_table WHERE id > 0";
    $result = mysqli_query($database_connection, $sql);

    $r = array();
    while ($row = mysqli_fetch_assoc($result)){
        $r[] = $row;
    }
    return $r;
}