Php PDO: Why does Inserting NULL yields to 0

2019-08-29 02:54发布

问题:

I searched any possible help that can be found online but still the problem with INSERT NULL using PHP PDO persists.

The script is a csvupload script originally came from here Import CSV into MySQL

To make the story short, Let me present the possible cause..

if($linearray[4]=='Unknown')
    $linearray[4]=null;
$linemysql = implode("','",$linearray);
$linemysql = "'".$linemysql."'";
$setsu->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$tsuika = $setsu->prepare("INSERT INTO tablename (SubAgentID, BookID, AgentID, SubAgentName, Risk, Area, CurrentBalance) VALUES ($linemysql)");
$tsuika -> bindValue(':Risk', null, PDO::PARAM_INT);
$tsuika ->execute();

Looking the code above, I explicitly set the field values on the prepare statment. On phpmyadmin the Risk field accepts NULL, set the default value to NULL, and has no problems. But when doing INSERT with PHP the value it gets is 0. Why?

Before Inserting, I echoed it and if the field $linearray[4] contains Unknown, it converts it to NULL yielding, '' for that part.

table structure

CREATE TABLE IF NOT EXISTS `subagentdb` (
`SubAgentID` int(10) NOT NULL AUTO_INCREMENT,
  `BookID` int(10) NOT NULL,
  `AgentID` int(10) NOT NULL,
  `SubAgentName` varchar(30) NOT NULL,
  `Risk` float DEFAULT NULL,
  `Area` varchar(20) NOT NULL,
  `CurrentBalance` float NOT NULL,
  PRIMARY KEY (`SubAgentID`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;

回答1:

You're binding the value explicitly as PDO::PARAM_INT. Whatever value you pass will be cast to an int because of that. null casts to 0.

To actually bind an SQL NULL value, you need to bind the value as PDO::PARAM_NULL.



回答2:

just use PDO::PARAM_NULL instead of PDO::PARAM_INT ? I think the NULL is converted to 0 (INT) instead of null value



标签: php mysql pdo null