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.
You could try with reflection:
With that we have an array which can be used as a lookup table:
For example:
getConstantswill 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_LOBandPARAM_INPUT_OUTPUT.