Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle boolean input in PHP PDO postgres?

Is there a better way to handle boolean inputs for postgres PDO driver in PHP?

In PHP PDO casts boolean false to "" and true to "1". And this causes an error like this in some statements:

00000 - 7 - ERROR:  invalid input syntax for type boolean: ""

I am passing my variables to PDOStatement::execute as input array.

For now I am using this workaround to pass appropriate string

':somevar'    => ($this->somevar === true ? 'true' : 'false')

Is there a better way?

I know about PDOStatement::bindParam with explicit data_type. I want to know the options for passing boolean in params array to the PDOStatement::execute().

UPDATE: added exact code

$qparams = array(
    ':id'            => $this->id,
    ':somevar'       => ($this->somevar === true ? 'true' : 'false'),
    ':updated_on'    => $timestamp
);

$sql = 'UPDATE ' . SONG_ARTISTS . ' SET ' .
    'id = :id, ' .
    'somevar = :somevar, ' .
    'updated_on = :updated_on ' .
    ' WHERE ' .
    ' id = :id';

$stmt = $pdo_handle->prepare($sql);
$result = $stmt->execute($params);
like image 941
Manmohan Bishnoi Avatar asked Aug 14 '15 14:08

Manmohan Bishnoi


1 Answers

By default PDO treats all data as strings. Bool false cast to string is the empty string. Postgres won't take the empty string for boolean false.

So no, there is no other way. Either you bind parameter as PDO_PARAM_BOOL or pretransform manually as you are doing now.

like image 128
Ivan Shagin Avatar answered Oct 13 '22 00:10

Ivan Shagin