1

I'm using PDO, and I managed to get the table columns despite the table name and create the bind variables, like in ... VALUES (:foo, :bar);.

The method I'm trying to do this is 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);        
 }
2
  • Post the relevant code too.. Commented Jun 8, 2015 at 13:31
  • Please add the code how you create your prepared statement, so we see which variables you used and so on Commented Jun 8, 2015 at 13:31

1 Answer 1

1

You have to loop over $data array and add function as per your requirement. Fetch values from `... VALUES (:foo, :bar); Then explode as you did in your code , then loop over $col array and add values to $data as required

foreach($col as $val){
    $method = "get".ucfirst( $val);
    $data[ $val] =  call_user_func(array( $this->entity,$method));
}

Above code may work as follow

$data[':foo'] =  $this->entity->getFoo();
$data[':bar'] =  $this->entity->getBar();
Sign up to request clarification or add additional context in comments.

2 Comments

Hello. I edited my question and tried to make it clearer about my need. Thank you. :)
Please replace $data = array( $col[$i] => "\$this->entity->get".ucfirst($col[$i])."()", ) with my code $data[$temp] = call_user_func(array( $this->entity,$method)); and try.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.