0

I am writing a code to generate dynamic prepared queries in PDO.

I have created an array that represents any table:

$tableUser=array(
    "name"=>"user",
    "columns"=>array(
        array("name"=>"user_id", "type"=>PDO::PARAM_INT),
        array("name"=>"user_name", "type"=>PDO::PARAM_STR),
        array("name"=>"user_lastname", "type"=>PDO::PARAM_STR),
    ),
);

I want to obtain an array with the columns and another array with the data types to use them later in the preparation of the query and for the bindParam.

This is my code:

$columns= array_column($tableUser["columns"], 'name');
$types= array_column($tableUser["columns"], 'type');

var_dump($columns);
var_dump($types);

Output:

array(3) {
  [0]=>
  string(7) "user_id"
  [1]=>
  string(9) "user_name"
  [2]=>
  string(13) "user_lastname"
}

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(2)
}

As you can see, the second var_dump shows me the values, not the names of the predefined constants.

Is there a way to get the names of the constants instead of the values? It's more out of curiosity and/or for clarity in the code, because I suppose that if I pass the values it will work correctly.

A. Cedano
  • 557
  • 7
  • 39
  • 1
    No. Those constants represent integers. There is no way to tie those back to the constant names. Why would you need them anyway? – Phil May 19 '23 at 00:08
  • no, if you need names, simply pass as string! But your requirement doesn't make sense. – OMi Shah May 19 '23 at 08:15

1 Answers1

0

You could try with reflection:

$pdoParamConstants =
  array_flip(
    array_filter(
      ( new ReflectionClass(PDO::class) )->getConstants(ReflectionClassConstant::IS_PUBLIC),
      static function (int $value, string $key): bool {
        return str_starts_with($key, 'PARAM_')
          && $value < 6
          && $value !== 4
          && !str_starts_with($key, 'PARAM_EVT');
      },
      ARRAY_FILTER_USE_BOTH
    )
  );

With that we have an array which can be used as a lookup table:

echo $pdoParamConstants[yourValueHere];

For example:

echo $pdoParamConstants[PDO::PARAM_STR];   // Output: 'PARAM_STR'
echo $pdoParamConstants[PDO::PARAM_INT];   // Output: 'PARAM_INT'

getConstants will return all constants (in this case we want only public constants, hence the argument to it). Then we have to filter out all non data type constants. And because the returned array is in the form of constantName => constantValue, we flip it, to get the lookup table.

Note that this does not work so simple if one of the following constants comes into play: PARAM_STR_NATL, PARAM_LOB and PARAM_INPUT_OUTPUT.

lukas.j
  • 6,453
  • 2
  • 5
  • 24