Php PDO: Why does Inserting NULL yields to 0

孤街浪徒 提交于 2019-12-12 04:06:44

问题


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



来源:https://stackoverflow.com/questions/25030447/php-pdo-why-does-inserting-null-yields-to-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!