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
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.
PHP Code to INSERT Data Into MySQL Database. There are two methods you can use to INSERT data into your MySQL database. The PHP MySQLi method and PHP Data Object or PDO method.
Description ¶ Prepares an SQL statement to be executed by the PDOStatement::execute() method. The statement template can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With