0

I am working the first time with prepare statements to prevent sql injections. I tried this code, which works fine:

$myInt      = "5";
$myTxt      = "Hello World";

$sql = $db->prepare("INSERT INTO `test` (`myInt`, `myTxt`, `myDate`, `myBool`) VALUES (?, ?, CURRENT_DATE(), NULL)");
$sql->bind_param("is", $myInt, $myTxt);

But why it works fine? $myInt is a string value. I set integer as bind_param type.

Can anyone explain me this situation ?

Trombone0904
  • 4,132
  • 8
  • 51
  • 104
  • 2
    It will be treated (and cast) as an int. And prepared statements are by nature safe from SQL injections since you're not injecting the values into the query itself. – M. Eriksson Feb 02 '22 at 17:48
  • ah okay, I see. thank you :) – Trombone0904 Feb 02 '22 at 17:49
  • 1
    For what it is worth, some people recommend always binding as `s`tring - https://stackoverflow.com/a/65530205/296555 & https://stackoverflow.com/a/58781505/296555 – waterloomatt Feb 02 '22 at 17:49
  • Are you asking why it accepts a string for an int value or are you asking why it prevent SQL injection? – Dharman Feb 02 '22 at 17:53
  • The PHP internal code for mysqli can cast the PHP variable to its integer numeric value as it reads it. The code is here: https://github.com/php/php-src/blob/master/ext/mysqli/mysqli_api.c#L218 – Bill Karwin Feb 02 '22 at 17:57

0 Answers0