0

I'm trying to do a simple select like this:

$productId = '241';

$stmt = $db->prepare('SELECT * FROM products WHERE id = ?');
$stmt->execute([ $productId ]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

It works, but if I change productId to this:

$productId = '241FJKSDFJKDSJKF';

it still brings me the product, whereas it should, since it doesn't match. Why is this happening?

I think I get it, id is primary key, auto increment so non numerical characters are being ignored, still I don't want this behaviour, is there any way to change it?

nick
  • 2,819
  • 5
  • 33
  • 69
  • 2
    Since the ID most likely is a column with integer as type, the string `241FJKSDFJKDSJKF` will be cast into: `241`. – M. Eriksson Dec 01 '20 at 22:42
  • @MagnusEriksson any way of preventing this? – nick Dec 01 '20 at 22:43
  • 1
    Screen your inputs and reject non-numerical data? – tadman Dec 01 '20 at 22:45
  • Not sure, but you could try and set the parameter with a type. Instead of binding the params by passing them to `execute()` (where all of them are treated as strings), try adding them with [bindParam()](https://www.php.net/manual/en/pdostatement.bindparam.php) and explicitly set the param as integer in the third argument. – M. Eriksson Dec 01 '20 at 22:51
  • *I don't want this behaviour*, then validate input is a number. – Lawrence Cherone Dec 01 '20 at 23:15

0 Answers0