2

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?

Dong3000
  • 566
  • 2
  • 7
  • 24
  • Try removing the `PDO::` from the third param – Abandoned Account Apr 30 '15 at 10:58
  • don't do it in a loop - explicitly declare each parameter binding. Doing these things in loops is a bit of an anti-pattern IMO... – Ian Wood Apr 30 '15 at 10:59
  • As you can see below, Rizier123's first solution is the best one. You just have to add `intval()` to complete it: `$stmt->bindParam(":$key", $program->$key, intval($value));`. – Dong3000 Apr 30 '15 at 11:42

1 Answers1

5

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"));
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • I concerned this solution. I was just wondering, if it's possible to combine PDO:: with a ariable... But thx! – Dong3000 Apr 30 '15 at 11:01
  • I would've answered this if you hadn't already, Really the only valid answer – Kris Apr 30 '15 at 11:06
  • @Dong3000 updated my answer with a solution which would work with the array which you have right now. But then you have to decide weather it's easier to just use the constant in the array definition itself or do an extra function call every iteration – Rizier123 Apr 30 '15 at 11:08
  • @Dong3000 What do you mean with: *Even if there are no inserted rows in my table* ? `constant()` doesn't have anything do to if your rows gets successfully inserted or not. – Rizier123 Apr 30 '15 at 11:33
  • 1
    You are right, @Rizier123, the first solution is the best one. But you have to `ìntval($value)` because it must be datatype long, not string. Thx for your hint! – Dong3000 Apr 30 '15 at 11:41