Mysqli无法在预准备语句中插入布尔值

时间:2018-05-08 08:02:32

标签: php mysqli

我试图通过php7将新行插入我的数据库。

Mysqli正在抛出错误

Column 'newsletter' cannot be null

数据库中的简报列是tinyint(1)

The database structure

以下是代码:

public function Add_User(array $data) {

    if( !isset($data['name']) || !isset($data['email']) || !isset($data['newsletter']) )

            $optin = ( $data['newsletter'] === 'on' ) ? 1 : 0;
            $country_code = $this->Get_Country_Code();

            if( !$q = $this->_db->prepare("INSERT INTO `users` (`name`,`email`,`country_code`,`newsletter`) VALUES (?,?,?,?)") ) { printf('error on prepare'); }
            if( !$q->bind_param('sssi', $data['name'], $data['email'], $country_code, $optin)) { printf('error on bind'); }
            if( !$q->execute() )  { printf('error on execute'); }

            printf('Insert error %s', $this->_db->error);

            if( $this->_db->affected_rows == 0 ) {
                // There was a problem with the insert  

                printf('Insert error %s', $this->_db->error);
            }

            $q->close();
    }

我也尝试将布尔值添加为字符串,但它仍然不起作用。

提前致谢。

3 个答案:

答案 0 :(得分:0)

你不应该将$ optin设置为true / false而不是1/0吗?

答案 1 :(得分:0)

if( !isset($data['name']) || !isset($data['email']) || !isset($data['newsletter']) )
    $optin = ( $data['newsletter'] === 'on' ) ? 1 : 0;

基本上如果这个标准不正确,那么你就不要输入"你的$ optin变量是否为null / undefined。

如果你想避免有两种方法。

1)更改db中newsletter字段中的接受值以接受null

2)

$optin=0;
if( !isset($data['name']) || !isset($data['email']) || !isset($data['newsletter']) ){
    if($data['newsletter'] === 'on' ){
        $optin=1;
    }
}

    $country_code = $this->Get_Country_Code();

使用"否定"定义您的变量如果您的条件不匹配,您希望设置的值,并在if。

中更改

答案 2 :(得分:0)

固定!

问题是我没有提供所有列值(我想稍后更新它们,因为它们在html表单提交时不可用)。

我需要为那些不会在初始INSERT上填充的列分配默认值。

但是错误消息没有帮助。

enter image description here