I have a function like the following:
function xxx( $sql, $params ) {
$query = $this->con->prepare( $sql );
$num = count( $params );
$pos = 0;
for ( $i=1; $i <= $num; $i++ ) {
$param = $params[ $pos ];
echo( "Parámetro " . $i . " -> " . $param . "<br>" ); //traza
$query->bindValue( $i, $param ); //$query->bindParam( 1, $param )
$pos++;
}
$query->execute( $params );
// ...
}
Where some possible parameters could be:
$sql = "INSERT INTO mi_tabla VALUES(NULL, ?, ?)";
$params = [ "Foo", NULL ];
To insert a new record in a table with the fields: id, nombre y edad
.
For edad
an integer is expected, but it also accepts null values , the problem comes when you pass a value NULL
, as a parameter, which does not bin. There is no error, the registration is simply not created.
I have tried to indicate the type of parameter as integer type (PDO::PARAM_INT)
and type NULL (PDO::PARAM_NULL)
, when the parameter is NULL
, but without result.
This is the configuration for the connection:
$options = [
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_OBJ,
\PDO::ATTR_EMULATE_PREPARES => FALSE, //Inactives emulated prepares
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
];
$options[] = ( $this->env === ( 'dev' || 'test' ))
? array( \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION )
: array( \PDO::ATTR_ERRMODE => \PDO::ERRMODE_SILENT );
try {
return new \PDO(
'mysql:host=' . $db_host .
';dbname=' . $this->db_name,
$this->db_user,
$this->db_pass,
$options
);
//...
Note : this example is simplified, the function must accept different statements with different groups of parameters.