What are common pitfalls when trying to store database query results in a PHP function?

One common pitfall when trying to store database query results in a PHP function is not properly handling the connection to the database within the function. To solve this, you should establish the database connection within the function itself and close it after fetching the results. Another pitfall is not properly handling errors that may occur during the query execution.

function getQueryResults() {
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "database";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT * FROM table";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // Output data of each row
        while($row = $result->fetch_assoc()) {
            echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
        }
    } else {
        echo "0 results";
    }

    $conn->close();
}

// Call the function to get query results
getQueryResults();