 <p>Call the function and save the result in a variable:</p> <pre><code>$result = GetProductsByCategory($categoryID); </code></pre> <p>then inside the function:</p> <pre><code>$productsResult = $conn-&gt;query($sql); return $productsResult; </code></pre> <p>then your while loop should use this returned result (i.e., <code>$result</code>):</p> <pre><code>while ($row = $result-&gt;fetch_assoc()) { ... } </code></pre>