Let's take this mysqli query:
$query = "SELECT * FROM table WHERE (".$id_type."=?)";
$id_type
is hard-coded and can be "userID"
(int(11)
in the mysql table) or "sessionID"
(char(36)
in the mysql table).
Can I just bind the parameters like this?
$stmt->bind_param('s', $id);
Is there a performance penalty or something else I should consider when using s
in bind_param
, even though $id
might be an int
? If not, why would I even bother in the future using the correct letters (i
, s
, d
, ...)?
It's always good to be as accurate as possible to reduce the risk of side effects/issues.
In your case, it should be pretty easy to do this.
$type = $id_type == 'userID' ? 'i' : 's';
$stmt->bind_param($type, $id);
That would work well if you only have two options.
If you have more, the below method would work.
$types = [
'userID' => 'i',
'sessionID' => 's',
];
$stmt->bind_param($types[$id_type], $id);
Then you can keep adding to your $types
array if you need more cols.