Insert php false in mysql

My MySQL table contains tinyint (1), which I use to store true or false.

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. Once the active variable is false, php inserts an empty string instead of 0, and therefore the request will fail.

What is the best method to use false in such a query?

Should I manually convert false to string '0'? Is it better to use bites on the PHP side right away? in other words declare: $ active = '1'; or can I somehow make PHP always convert false to string '0'?

Thanks michael

+4
source share
3 answers

First of all, your values ​​should be escaped using mysql_real_escape_string or mysqli_real_escape_string or another method suitable for your connection to the database to avoid sql code injection, then for your specific question regarding false, you can do something like this:

 $query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".($active?1:0) .")"; 

or throwing $ active into int should also be done:

 $query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".((int) $active)).")"; 
+4
source

Convert the variable to int:

 intval($active) 
+6
source

use mysql_real_escape_string ...

 $query = "INSERT into my_table (my_name, my_description, active) VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($description)."', ".mysql_real_escape_string (((int) $active))).")"; 
0
source

Source: https://habr.com/ru/post/1388031/


All Articles