12

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);
4
  • Please show the exact code you're using to prepare & bind the parameters. Commented Aug 14, 2015 at 14:11
  • @deceze I've added more code with the question. Commented Aug 14, 2015 at 15:00
  • Have you tried disabling EMULATE_PREPARES? Commented Aug 14, 2015 at 15:03
  • yes, tried EMULATE_PREPARES. Does not work. Commented Aug 14, 2015 at 15:57

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.