0

I'm trying to make a search bar with PHP to show the product that we got in store with a get script. Now I want to put the variable I get in my SQL query like this:

$search = $_GET['q'];

$sql = "SELECT
`product`.`productcode`,
`product`.`productnaam`,
`product`.`prijs`,
`product`.`voorraad`,
`afbeelding`.`image_id`,
`afbeelding`.`image_ctgy`
FROM `product`, `afbeelding`
WHERE `product`.`productcode` = `afbeelding`.`image_id` AND `afbeelding`.`image_ctgy` = $search
GROUP BY `productnaam`
ORDER BY `productnaam`;";

How do I make it so the variable doesn't mess with the query?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

3 Answers3

3

Take a look at PDO prepared statements.

They allow you to use a variable inside your query without worrying about MySQL injections too much.

$stmt = $dbh->prepare("SELECT
    `product`.`productcode`,
    `product`.`productnaam`,
    `product`.`prijs`,
    `product`.`voorraad`,
    `afbeelding`.`image_id`,
    `afbeelding`.`image_ctgy`
    FROM `product`, `afbeelding`
    WHERE `product`.`productcode` = `afbeelding`.`image_id` AND `afbeelding`.`image_ctgy` = :search
    GROUP BY `productnaam`
    ORDER BY `productnaam`");

$stmt->bindParam(':search', $search);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tewdyn
  • 687
  • 3
  • 16
1
$search = mysqli_real_escape_string($_GET['q']);

$sql = "SELECT product.productcode, product.productnaam,  product.prijs, product.voorraad, afbeelding.image_id, afbeelding.image_ctgy FROM    product, afbeelding WHERE product.productcode = afbeelding.image_id AND afbeelding.image_ctgy = '" . $search . "' GROUP BY productnaam ORDER BY productnaam";

Or use PDO instead (OOP):

$dbh = new mysqli($servername, $username, $password, $dbname);

$stmt = $dbh->prepare("SELECT product.productcode, product.productnaam,  product.prijs, product.voorraad, afbeelding.image_id, afbeelding.image_ctgy FROM    product, afbeelding WHERE product.productcode = afbeelding.image_id AND afbeelding.image_ctgy = :search GROUP BY productnaam ORDER BY productnaam");

if ($stmt->execute([':search' => $_GET['q']])) {
    while ($row = $stmt->fetch()) {
        print_r($row);
    }
}

If you're using an older version of php, replace [':search' => $_GET['q']] with array(':search' => $_GET['q'])

schellingerht
  • 5,726
  • 2
  • 28
  • 56
0

Use filter_input(). It will make sure the send $_GET variable is a secure string.

In your example:

// q is the name of the $_GET variable.
$search = filter_input(INPUT_GET, 'q', FILTER_SANITIZE_SPECIAL_CHARS);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Loai Abdelhalim
  • 1,901
  • 4
  • 24
  • 28