I want to dynamically determine the data type of input values I am getting from my HTML input form.this will assist me to bind parameter values of data I am inserting into my da
As pointed out in another answer all your values coming from HTML are strings. However, you might be having input coming from other sources, which you would like to pass to your statement. What would happen if you used string binding all the time?
Best way is to test it.
$data1 = '1';
$data2 = 2;
$data3 = '0.5-a';
$stmt = $mysqli->prepare('SELECT ?=1 AS f1, ?="2" AS f2, ?=0.5 AS f3');
$stmt->bind_param('sss', $data1, $data2, $data3); // binding string
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
var_dump($row); // all true
In these simple examples, there is no difference. Why? Because MySQL will cast a string to appropriate type if it is used in a numeric context.
Why specify a type explicitly if almost everything can be sent as a string?
Because if you know the data type of your values, you shouldn't be casting them back and forth. If you have integers and you use them in MySQL in numeric context then there is no reason to cast them to a string in MySQLi bind_param()
.
Another important use case is when MySQL really makes a distinction in the types, e.g. in ORDER BY
clause. If you bind a string instead of number, the order will be different. MySQL can either take an ordinal number representing the column number in SELECT
or a column name(which cannot be bound) or a string literal.
$data1 = '2';
// I want the records to be ordered by `name`, which is the second column
$stmt = $mysqli->prepare('SELECT id, name FROM products ORDER BY ?');
$stmt->bind_param('i', $data1); // binding integer instead of string
Related post: mysqli_stmt::bind_param() - specify another data type than “s” for each parameter
When it comes to binary or blob, they are just binary strings. This means they have no character set, and sorting and comparison are based on the numeric values of the bytes in column values.
If you ever find yourself needing to insert a blob value, it will most likely not come from HTML form as a string, but rather from reading in a file and you will know that you need to use b
.