我正在使用PDO,尽管有表名,我设法获取表列并创建绑定变量,如... VALUES (:foo, :bar);
中所示。
我尝试执行此操作的方法是insert()
。
public function insert()
{
// the variable names depend on what table is being used at the moment the script runs.
// These methods use the PDO `getColumnMeta()` to retrieve the name of each column
$sql = "INSERT INTO {$this->getTableName()}({$this->getTableColumns()}) "
. "VALUES ({$this->getTableColumns(true)})";
// The previous method gets the name of each column and returns a single string, like "foo, bar, [...]"
// and this function is used to separate each word, with the specified delimiter
$col = explode(", ", $this->getTableColumns());
// Now here lays the problem.
// I already know how to retrieve the columns name as a variable, and
// how to dynamically create the get method, using `ucfirst()`
// What I need would be something like this being inside of a
// loop to retrieve all the separated words from `$col` array.
$data = array(
$col[$i] => "\$this->entity->get".ucfirst($col[$i])."()",
)
/*
* From now on, is what I need to do.
*/
// Lets pretend the column names are "foo, bar".
$data = array(
":foo" => $this->entity->getFoo(),
":bar" => $this->entity->getBar()
)
// That'd be the final array I need, and then continue with
$stm = $this->db->prepare($sql);
$stm->execute($data);
}
答案 0 :(得分:1)
您必须遍历$ data数组并根据您的要求添加函数。 从`... VALUES(:foo,:bar)中获取值;然后像在代码中一样爆炸,然后遍历$ col数组并根据需要向$ data添加值
foreach($col as $val){
$method = "get".ucfirst( $val);
$data[ $val] = call_user_func(array( $this->entity,$method));
}
以上代码可能如下工作
$data[':foo'] = $this->entity->getFoo();
$data[':bar'] = $this->entity->getBar();