Adariel Lzinski Adariel Lzinski - 11 months ago 45
HTML Question

How to get information from database file, and retrieve that information in the website file?

I'm in the process of doing a "mock" website for a class and I'm having issues getting the information from my database file, to the actual page in my site. I should mention that I'm a total php newb. Also there isn't any security yet.

I'm calling the connection from another file, so I didn't include that.

database function:

function GetProductsByCategory($categoryID) {
global $conn, $productsResult;
echo $categoryID;
$sql = "SELECT * FROM products WHERE prodCategory = '$categoryID'";
$productsResult = $conn->query($sql);

Website File:

//In the head of website file
$categoryID = "87";
if (isset($_GET['category'])) {
} else {
// Fallback behaviour goes here

//In the body
<?php while ($row = $productsResult->fetch_assoc()) {
//Just trying to get information from the database file
echo '<div>'.$row["prodName"].'</div>';

I should mention that nothing throws an error, It echos out the category ID at the top, but inside the
it just doesn't show anything.

Answer Source

Call the function and save the result in a variable:

$result = GetProductsByCategory($categoryID);

then inside the function:

$productsResult = $conn->query($sql);
return $productsResult;

then your while loop should use this returned result (i.e., $result):

while ($row = $result->fetch_assoc()) { ... }