-1

this is the first time I'm using PDO and I'm trying to create a function to inserting data in a table just by passing 3 parameters.

This is the function:

public function insert($t, $v, $r)
    {
        if ($this->active)
        {
            if (($t != null) && ($r != null) && ($v != null) && (count($v) == count($r)))
            {
                $instruction = 'INSERT INTO `' . DBNAME . '`.`' . $t . '` (';

                for ($i = 0; $i < count($r); $i++)
                    $_r[$i] = '`' . $r[$i] . '`';
                $_r = implode(',', $_r);

                $instruction .= $_r . ') VALUES (';

                for ($i = 0; $i < count($r); $i++)
                    $r[$i] = ':' . $r[$i];
                $r = implode(',', $r);

                $instruction .= $r . ');';

                $statement = $this->PDO->prepare($instruction);

                for ($i = 0; $i < count($r); $i++)
                    $statement->bindParam($r[$i], $v[$i]);

                $statement->execute();
                echo $instruction;
                return true;
            } else
                return false;
        } else
            return false;
    }

I tried this:

$t = "users";
$v = array(201);
$r = array("id_user");

$data->insert($t, $v, $r);

But it doesn't work. That's what it returns:

Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in /Applications/XAMPP/xamppfiles/htdocs/friz/mysql_functions.php on line 68 INSERT INTO friz.users (id_user) VALUES (:id_user);

Can you help me?

P.S.: I used the search function, but I didn't find anything to solve my problem.

4

1 回答 1

2

Your line

$r = implode(',', $r);

converts $r from an array to a string;

so it no longer contains an array of names when you try to bind; so $r[$i] will simply be the first character of the string $r which is a ':'

    for ($i = 0; $i < count($r); $i++)
        $_r1[$i] = '`' . $r[$i] . '`';
    $_r1 = implode(',', $_r1);

    $instruction .= $_r1 . ') VALUES (';

    for ($i = 0; $i < count($r); $i++)
        $_r2[$i] = ':' . $r[$i];
    $_r2 = implode(',', $_r2);

    $instruction .= $_r2 . ');';

will leave $r as an array

于 2013-06-29T14:55:13.953 回答