Search code examples
phpmysqlphalcon

Phalcon : Exception: Wrong number of parameters


I want to execute a prepared insert :

<?php
function add_record($tab) {

        $champs= "";
        $value = "";
        $separateur ="";
        $ins = array();

        foreach ($tab as $k => $v){
            $champs .= $separateur . $k;
            $value .= $separateur . "?" ;
            $ins[] = $v;
            $separateur = ",";
        }
        $champs = '('.$champs.')';
        $value = '('.$value.')';

        $sSQL = "INSERT INTO facture $champs VALUES $value";

        executePreparedDML($sSQL, $ins);

    }

    function executePreparedDML($sSQL, $tab) {
    $config = array(
        "host" => SERVEUR,
        "dbname" => BDD,
        "port" => BDD_PORT,
        "username" => LOGIN_DB,
        "password" => PWS_DB);
    $connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config);
    $statement = $connection->prepare($sSQL);
    $pdoResult = $connection->executePrepared($statement, $tab);
}
?>

When executing the add_record function then I got this error : Exception: Wrong number of parameters ! So what is wrong ?


Solution

  • According to manual:

    public PDOStatement executePrepared (PDOStatement $statement, array $placeholders, array $dataTypes)

    Executes a prepared statement binding. This function uses integer indexes starting from zero

    In other part of manual we can see that Phalcon allows bindings of names eg. = :email or bindings indexed as of ?0, ?1.

    As you function is serving array of [0 => 'first', 1 => 'second'], i would test to create chain like (?0, ?1, ?2, ?3, ?4) instead of (?,?,?,?,?).

    You can also try to not prepare it the way you are doing it in question example and go straight for version from your own answer.

    Also, when using models it is as easy as:

    $obj = new credentialModel();
    $isOk = $obj->save(array(
        'name' => 'John',
        'surname' => 'Doe'
    ));
    

    and once you are using Phalcon, I would recommend to actually use it.