Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

specifying mysqli bind_param types

what are the pros and cons of specifying mysqli bind_param types i,d,s,b?

I store a UNIX timestamp in a db column with data type INT. In my prepared statement I set it to bind_param('s',$timestamp); and it stores the value without any problems. So what impact did it make that I used s instead of i during bind_param?

like image 354
Jo E. Avatar asked Oct 29 '25 15:10

Jo E.


1 Answers

It influences how MySQL will see the query/value. Take this query:

INSERT INTO foo VALUES (?)

If you bind the parameter as int:

$stmt->bind_param('i', $bar);

Then the query will be about equivalent to:

INSERT INTO foo VALUES (42)

However, if you bind as string:

$stmt->bind_param('s', $bar);

The query will be about equivalent to:

INSERT INTO foo VALUES ('42')

In many cases MySQL doesn't particularly care whether you send it a string or an int and will simply cast the value to the appropriate type on the fly, just as PHP does most of the time. However, in some circumstances and with some types you may get an unexpected conversion, which is why you should bind the value as the type that you want it as and not leave it up to MySQL's casting rules.

like image 60
deceze Avatar answered Oct 31 '25 07:10

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!