My MySQL table contains a tinyint(1) value that i use to store a true or false value.
I have the following PHP variables:
$name = '';
$description = '';
$active = true;
Now my SQL query is as follows:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', $active) ";
This will only work if my value for $active is true. As soon as the active variable is false, php will insert an empty string, instead of a 0 and thus the query will fail.
What is the best method to use false in such a query?
Should i manually convert the false to a '0' string? Is it better use stings on the PHP side right away? in other words declare: $active = '1'; or can i somehow get PHP to always convert false to a '0' string?
Thanks Michael
Convert your variable to int:
intval($active)
First of all your values should be escaped using mysql_real_escape_string or mysqli_real_escape_string or other method suitable for your database connection to avoid sql injection then for your specific question regarding false you may do something like that:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".($active?1:0) .")";
or casting $active to int should do the work too:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".((int) $active)).")";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With