Warren Warren - 10 days ago 5
PHP Question

How does PHP's is_bool tell the difference between INT and BOOL?

I ask because I'm having issues passing a boolean value to PDO.

This function gives me True/False:

public function getBoolVal($var){
if (!is_string($var)) return (bool) $var;
switch (strtolower($var)) {
case '1':
case 'true':
case 'on':
case 'yes':
case 'y':
return true;
default:
return false;
}
}


I'm binding data to parameters inside a function with a line like this:

$this->db->bind('active', (bool)$this->getBoolVal($pa['active']));


and inside that
bind
function is:

foreach ($this->parameters as $param => $value) {
$type = PDO::PARAM_STR;
switch ($value[1]) {
case is_int($value[1]):
$type = PDO::PARAM_INT;
break;
case is_bool($value[1]):
$type = PDO::PARAM_BOOL;
break;
case is_null($value[1]):
$type = PDO::PARAM_NULL;
break;
}
// Add type when binding the values to the column
$this->sQuery->bindValue($value[0], $value[1], $type);
}


When the values are bound, I get
PDO::PARAM_BOOL
as the type when the input value
$pa['active']
is 1, but I always get
PDO::PARAM_INT
if the input is 0...

So given a 1 or 0, how on Earth does
is_bool
know what I want??? OR how can I fix this?

Answer

you can change your code as

if ($value[1] === true or $value[1] === false) {
    $type = PDO::PARAM_BOOL;
}
else {
    switch ($value[1]) {
        case is_int($value[1]):
            $type = PDO::PARAM_INT;
            break;
        case is_float($value[1]):
            $value[1] = str_replace(',', '.', $value[1]);//already string, pdo does not support float values
            break;
        case is_null($value[1]):
            $type = PDO::PARAM_NULL;
            break;
    }
}