Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a PHP false into mysql

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

like image 266
Michael Frey Avatar asked Dec 26 '11 15:12

Michael Frey


2 Answers

Convert your variable to int:

intval($active)
like image 70
ssbb Avatar answered Oct 31 '22 23:10

ssbb


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)).")";
like image 27
malko Avatar answered Nov 01 '22 00:11

malko