2
\$\begingroup\$

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->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->bind_result(
    $username,
    $quantity,
    $description,
    $product_name);
$stmt->execute();

while($stmt->fetch()){
echo $product_name;
}
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.