Parameterized queries in PHP with phpmyadmin connexion

I'm trying to show in a website the products whitch inside in a category. I achived show the products of one category if I put the number of my category manually. However, I don't know how to show the products of a specific category by accessing the data in my database without putting the id of the category manually before my query but by accessing the id of the table of categories that this related to the category_id of my product table.

<?php

function muestraProd($DB)
{
    $productos=NULL;
    $categoria_id = 1;

    $sql = 'SELECT * FROM producto WHERE categoria_id = ?';
    
    $stmt = $DB->prepare($sql);
    $params = [$categoria_id,];
    $stmt->execute($params);
    $productos = $stmt->fetchAll();
    return $productos;
}

Upvotes: 0

Views: 569

Answers (1)

Rasclatt
Rasclatt

Reputation: 12505

As noted in the comments above, you adjust your function to accept the category as a parameter to the function, then you can call it and use it anywhere in your script:

<?php
function muestraProd($id, $DB)
{
    if(empty($id))
        return null;
    $stmt = $DB->prepare('SELECT * FROM producto WHERE categoria_id = ?');
    $stmt->execute([$id]);
    return $stmt->fetchAll();
}

Now that your function accepts the id as a parameter, you can use it where ever, as long as you include this function in your script. On form submit:

# This will insert the id assuming it is submitted in a form
$prod = muestraProd(($_POST['id'])?? false, $DB);

If in a query (as noted in comments) https://www.emample.com?id=1:

$prod = muestraProd(($_GET['id'])?? false, $DB);

Then you can just manually if you wanted to:

$prod = muestraProd(1, $DB);

These are the most common ways.

Upvotes: 1

Related Questions