0

I created a function that read data from a mysql db.

I want to put the data into a array and read that outside of the PHP function.

function showCategory($con) {
    $sql = "SELECT * FROM kategorien";
    $kategorien = array();     

    $result = $con->query($sql);
    while($row = $result->fetch_assoc()) {
        $kategorien[] = $row["kategorie"];
        return $kategorien;
    }   
}

To load the data outside from function:

$kategorien = showCategory($con);
echo $kategorien['kategorie'][0];

It doesn't work. Whats wrong?

1
  • 1
    First try return $kategorien; outside the While loop because return naturally ends execution of the current function Commented Jan 24, 2019 at 10:07

2 Answers 2

2

The

return $kategorien; 

will exit the loop and the function, so move this to the end of the function and not in the loop.

function showCategory($con) {
    $sql = "SELECT kategorie FROM kategorien";
    $kategorien = array();     

    $result = $con->query($sql);
    while($row = $result->fetch_assoc()) {
        $kategorien[] = $row["kategorie"];
    }   
    return $kategorien;
}

Rather than using *, it's also worth specifying the column names if you only need some of them.

Display the data using...

$kategorien = showCategory($con);
print_r( $kategorien );

or use a foreach()...

$kategorien = showCategory($con);
foreach ( $kategorien as $kat ) {
    echo $kat.PHP_EOL;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! But i'm only get only the first entry ... $kategorien = showCategory($con); echo $kategorien[0];
Try print_r($kategorien) instead the echo
@NigelRen you can do array_column as return array_column($result, 'kategorie'); and not use the while loop (if used fetch_assoc_all)
I've added a few more options to display the data - but $kategorien[0] is only the first element of the array ([0])
0

Use this instead, because returning $kategorien will exit the loop, so it will only run once.

function showCategory($con) {
    $sql = "SELECT * FROM kategorien";
    $kategorien = array();     

        $result = $con->query($sql);
            while($row = $result->fetch_assoc()) {
               $kategorien[] = $row["kategorie"];
            }  
            return $kategorien;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.