问题
How do I insert a BIT value in MySQL using a PDO Prepared Statement? Below is what I tried and my results.
<?php
function testIt($value)
{
$sql='INSERT INTO test(id,data) VALUES(?,?)';
$stmt=db::db()->prepare($sql);
$stmt->execute(array(0,$value));
$id=db::db()->lastInsertId();
$sql='SELECT * FROM test WHERE id='.$id;
$stmt=db::db()->query($sql);
$rs=$stmt->fetch(PDO::FETCH_ASSOC);
echo("Test for {$value} returns id {$rs['id']} and data {$rs['data']}<br>");
}
date_default_timezone_set('America/Los_Angeles');
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once('../../ayb_private/dbase.php');
$sql='CREATE TEMPORARY TABLE test (id INT UNSIGNED NOT NULL AUTO_INCREMENT, data BIT(8) NOT NULL DEFAULT 00000000, PRIMARY KEY (id) )';
$stmt=db::db()->exec($sql);
testIt('b"01010101"');
testIt('b01010101');
testIt('01010101');
testIt(0x55);
testIt("b'01010101'");
?>
RESULTS:
Test for b"01010101" returns id 1 and data 255
Test for b01010101 returns id 2 and data 255
Test for 01010101 returns id 3 and data 255
Test for 85 returns id 4 and data 255
Test for b'01010101' returns id 5 and data 255
回答1:
Not near a terminal to check, but I believe you have to type bind it to INT and send it in as an INT, not as "b010101" (or whatever):
$sql='INSERT INTO test(id,data) VALUES(:id,:bit)';
$stmt=db::db()->prepare($sql);
$stmt->bindValue('id', null, PDO::PARAM_NULL);
$stmt->bindValue('bit', (int)$value, PDO::PARAM_INT);
$stmt->execute();
Quick check on Google brought up this similar previous answer.
来源:https://stackoverflow.com/questions/25570070/insert-bit-value-in-mysql-using-pdo-prepared-statement