简体   繁体   English

在预处理语句PDO PHP中绑定值数组

[英]Binding array of values in prepared statement PDO PHP

I'm trying to bind my values into a prepared statement in PDO. 我正在尝试将我的值绑定到PDO中的预准备语句中。

Here is the pre requisite codes that that uses the prepared statement block: 以下是使用预准备语句块的先决条件代码:

$tab = 'air_user';
$fie = array('USER_NAME', 'USER_PASSWORD' , 'USER_EMAIL');
$name = $_POST['name'];
$pass = $_POST['password'];
$email = $_POST['email'];
$val = array(
    'name' => $name,
    'pass' => $pass,
    'email' => $email
);
$this->connect($tab,$fie,$val);

And here is the part wherein I prepare those values and make the necessaru insertions: 以下是我准备这些值并进行必要插入的部分:

public function connect($table,$fields,$values)
{

    try{
        $con = new PDO ('mysql:host=localhost;dbname=air','root','123456');
        $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        $fields = implode(", ", $fields);
        echo $fields;
        $values = implode(", ", $values);
        echo $values;

        // have to make this prevent sql injection //
        $stmt = $con->prepare("INSERT INTO $table(ID,$fields) VALUES (?,?,?,?)");
        $stmt->execute(array('',$values));

    } catch(PDOException $e) {
        die("this cant connect the database");
    }
}

so why isit my INSERT not Working ? 那么为什么我的INSERT不工作? isit can anyone help me take a look of it , i tryed so many things , none of them work. 任何人都可以帮助我看看它,我尝试了很多东西,没有一个工作。

No, don't implode the values that your going to pass inside the ->execute() , it must be an array: 不,不要implode你要在->execute()内传递的值,它必须是一个数组:

$fields = implode(", ", $fields);
// $values = implode(", ", $values); // DONT IMPLODE!
$values = array_values($values);

$stmt = $con->prepare("INSERT INTO $table(ID,$fields) VALUES (NULL, ?,?,?)");
$stmt->execute($values);

Or @Augwa's suggestion: 或@ Augwa的建议:

// $fields = implode(", ", $fields); // not needed
// $values = implode(", ", $values); // DONT IMPLODE!

$placeholders = substr(str_repeat('?,', sizeOf($fields)), 0, -1);
// $placeholders = implode(', ', array_fill(0, count($values), '?'));

$stmt = $con->prepare(
    sprintf(
        "INSERT INTO %s (%s) VALUES (%s)", 
        $table, 
        implode(',', $fields), 
        $placeholders
    )
);
$stmt->execute($values);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM