如何将数据插入到位数据类型的字段中


How do I insert data into a field of bit data type?

尝试将新记录插入数据库时遇到问题。我认为问题出在位字段上。当我分配值 True 时,出现此错误:

Failed: Array ( [0] => Array ( [0] => 22018 [SQLSTATE] => 22018 [1] 
=> 245 [code] => 245 [2] => [Microsoft][SQL Server Native Client 10.0]
[SQL Server]Conversion failed when converting the varchar value ' 1 ' 
to data type bit. [message] => [Microsoft][SQL Server Native Client 10.0]
[SQL Server]Conversion failed when converting the varchar value ' 1 ' to 
data type bit. ) )

但是如果我将其更改为 false,它可以工作。我将展示我的一些代码。我已经删除了大部分内容,因为我已将其缩小到此变量:

$active = True;

这是我的插入查询。

$sqlInsert = "INSERT INTO customers(
                customerID,
                registeredDate,
                givenName,
                familyName,
                email,
                password,
                phone,
                mobile,
                property,
                street,
                locality,
                town,
                area,
                postalCode,
                active
            ) 
            VALUES(" .
                $newUser . "," .
                $date . ", ' " .
                $given . " ', ' " .
                $family . " ', ' " .
                $email . " ', ' " .
                $pwd . " ', ' " .
                $phone . " ', ' " .
                $mob . " ', ' " .
                $property . " ', ' " .
                $street . " ', ' " .
                $locality . " ' , ' " .
                $town . " ', ' " .
                $area . " ', ' " .
                $postalcode . " ', ' " .
                $active . " ')";
$stmtInsert = sqlsrv_query($conn, $sqlInsert);

我假设active字段是bit数据类型。

您不要像对 customerid 字段那样在为活动字段传递的值两边使用任何引号。

另外,我认为您必须将值/转换为 1/0

修改后的代码:注意到" . $active . "周围的单引号已被删除。

$sqlInsert = "INSERT INTO customers(customerID, registeredDate, givenName,
                familyName,  email, password, 
                phone, mobile, property, 
                street, locality, town,  
                area, postalCode, active) 
              VALUES(" . $newUser . "," . $date . ", ' " . $given . " ', 
              ' " . $family . " ', ' " . $email . " ', ' " . $pwd . " ', 
              ' " . $phone . " ', ' " . $mob . " ', ' " . $property . " ', 
              ' " . $street . " ', ' " . $locality . " ' , ' " . $town . " ', 
              ' " . $area . " ', ' " . $postalcode . " ', " . $active . ")";
$stmtInsert = sqlsrv_query($conn, $sqlInsert);

我不确定为什么它适用于 False 值。我建议您在设置所有值后了解INSERT语句的计算结果。不要执行该语句,而是将 INSERT 语句打印到屏幕/页面,并在 SQL Server Management Studio 中针对数据库手动运行它。