Hi community,
I am trying to manage a dynamic binding but cannot get it to work. Here is the situation:
I take the metadata of a table and load it into a variable
$meta = Yii::app()->db->schema->getTable($table)->columnNames;
$lastID = count($meta)-1;
Next I dynamically create an SQL query:
foreach($meta as $n=>$field)
{
if($n == '0'){
$values .= $field.', ';
$placeholder .= ':'.$field.', ';
}elseif($n == $lastID){
$values .= $field.'';
$placeholder .= ':'.$field;
}else{
$values .= $field.', ';
$placeholder .= ':'.$field.', ';
}
}
$sql = "INSERT INTO ".$table." (".$values.") VALUES(".$placeholder.")";
$command = Yii::app()->db->createCommand($sql);
So far works like a charm but here is where it fails. I have csv lines that I would like to load into DB so I iterate each line with an explode and attempt to bind each value to the query above, however unsuccessfully:
for($x=0; $x<=count($lineDump)-1; $x++)
{
$command->bindValue('":'.$meta[$x].'"', $lineDump[$x]);
}
The above code iterates 13 times but not the way I would expect it to.
$meta[] - is the array with the table’s metadata; $lineDump[] - array containing part of a csv line that needs to go into DB. This last part does not work and throws an error that I have declared incorrect number of parameters. When I go with hardcoding the params like this works fine:
$command->bindValue(':id', $lineDump[0]);
$command->bindValue(':field1', $lineDump[1]);
$command->bindValue(':field2', $lineDump[2]);
However, this is not an option as I would like to automate this. Is there a correct way to automate the value binding process?
Cheers,
bettor