简体   繁体   中英

PHP - MySQL trying to set value=“0” - it's NULL

I'm just trying to set some value = "0", but it's automatically convert into NULL.

$result_checkups = mysql_query("INSERT INTO TABLE1 (COL1, COL2) VALUES (".(!empty($COL1) ? "'$COL1'" : "NULL").", ".(!empty($COL2) ? "'$COL2'" : "NULL").") or die(mysql_error());

It's my code - it look so strange, becouse I need to set NULL, when someone trying to set empty string (""). But now, when COL2="0" , then it's NULL behind MySQL (to clear, when COL2="1" , it's "1" behind MySQL). Where is problem?

MySQL table:

CREATE TABLE `TABLE1` (
  `COL1` TIMESTAMP NULL DEFAULT NOW(),
  `COL2` TINYINT(1) NULL);

Because of

php -r 'echo empty(0);'
1
php -r 'echo empty("0");'
1

0 is empty. Try to change your statement to:

$result_checkups = mysql_query("INSERT INTO TABLE1 (COL1, COL2) VALUES (".(($COL1==='') ?  "NULL" : "'$COL1'").", ".(($COL2==='') ? "NULL" : "'$COL2'").")") or die(mysql_error());
  1. Clean up your data with escape function to prevent sql-injection ;
  2. Predefine data BEFORE insertion into query - it is cleaner and more readable.
  3. Read empty() function documentation:

The following things are considered to be empty:

"" (an empty string)

0 (0 as an integer)

0.0 (0 as a float)

"0" (0 as a string)

NULL

FALSE

array() (an empty array)

$var; (a variable declared, but without a value)

So "0" is considered empty. I suggest you to use strlen() instead.

Try this:

$COL1 = mysql_real_escape_string($COL1);
$COL2 = mysql_real_escape_string($COL2);

$COL1 = strlen($COL1) ? $COL1 : 'NULL';
$COL2 = strlen($COL2) ? $COL2 : 'NULL';

$sql  = "INSERT INTO TABLE1 (COL1, COL2) VALUES ({$COL1}, {$COL2})";

$result_checkups = mysql_query($sql) or die(mysql_error());

PS: MySQL extension is deprecated. Use MySQLi or PDO instead. Follow this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM