Prepared statement inside function that then return results I've created a function that makes a query of a database table and managed to use the results in another page where the function is called.

Is this approach good?

function cart_list($db, $user){
    $stmt = $db-&gt;prepare("
SELECT 
    o.username,
    o.quantity,
    p.description,
    p.product_name,
FROM 
    orders as o
INNER JOIN 
    products as p
ON
    p.product_id = o.product_id
INNER JOIN 
    users as u
ON
    o.username = u.username
WHERE 
    o.username ='$user'
AND
    o.checkout ='0'");
return $stmt;
}


In the file where I called the function, I used:

$stmt = cart_list($db, $user);
$stmt-&gt;bind_result(
    $username,
    $quantity,
    $description,
    $product_name);
$stmt-&gt;execute();

while($stmt-&gt;fetch()){
echo $product_name;
}
To begin, your indentation is a little off at places, such as in the while loop in the second code block, or the return statement in the first.



It looks like you keep o.checkout as an integers like the = '0' suggests, but use strings, as the '' suggests. If you do measure solely in integers, you ought to change the database type.




WHERE 
    o.username ='$user'



You should use bind_param() instead of straight injection, as it's safer for sanitisation.