Search code examples
phpmysqlarrayspdobindparam

PDO bindParam variable datatype from array


I have an array which relates mysql-colums to PDO datatypes:

$imp->datafields=array(
  "id"           => "PARAM_INT",
  "name"         => "PARAM_STR",
  "cookieLength" => "PARAM_INT"
);

I want to bind these parameters using foreach()

foreach($imp->datafields AS $key => $value) {
   $stmt->bindParam(':$key', $program->$key, PDO::$value);
}

and get this error:

PHP Fatal error:  Access to undeclared static property: PDO::$value

How can I solve this problem?


Solution

  • Just change your array definition to use the PDO constants like this:

    $imp->datafields=array(
      "id"           => PDO::PARAM_INT,
      "name"         => PDO::PARAM_STR,
      "cookieLength" => PDO::PARAM_INT
    );
    

    And then in your foreach loop just use $value alone like this:

    $stmt->bindParam(":$key", $program->$key, $value);
                   //^     ^                  ^^^^^^
    

    And also use double quotes that the variables gets parsed in it!

    What you could also do if you really want it just to use constant() in every iteration like this:

    $stmt->bindParam(":$key", $program->$key, constant("PDO::$value"));