将函数内的值绑定到INSERT INTO DB

时间:2013-10-16 00:37:50

标签: php arrays pdo mysqli

假设我有这段代码:

$array = array('one' => $one, 'two' => $two);
$sql->sql_insert('table_name', $array);

我有类对象$sql和函数sql_insert但是我如何使用mysqli预处理语句来绑定值并将其插入到数据库中?我们可以说mysqli connection$this->connection

任何建议都会非常感谢。

编辑:

function sql_insert_bind($table, $insert){

    $count = count($insert);
    $bind_val = '';
    for($i = 0; $i <= $count; $i++){

        $bind_val .= '?, ';
    }

    $query = $this->connection->prepare('INSERT INTO `'.$table.'` VALUES ('.substr($bind_val, 0, -2).')');

    foreach($insert as $key => $value){

        $query->bind_param($key, $value);
    }

    $query->execute();
}

我收到错误消息:Fatal error: Call to a member function bind_param() on a non-object$this->connection是mysqli对象

2 个答案:

答案 0 :(得分:2)

好的,这就是我如何使用PDO(自OP询问)

我假设你已经将一个PDO对象实例化或注入到你的类中作为$connection属性,例如

class SQLClass {
    /**
     * @var PDO
     */
    private $connection;

    public function __construct(PDO $pdo) {
        $this->connection = $pdo;
    }

    // etc
}

$pdo = new PDO('mysql:host=localhost;dbname=db_name;charset=utf8', 'username', 'password', array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC));

$sql = new SQLClass($pdo); 

然后,在您的sql_insert_bind方法

$keys = array_keys($insert);

$cols = array_map(function($key) {
    return sprintf('`%s`', $key);
}, $keys);

$placeholders = array_map(function($key) {
    return sprintf(':%s', $key);
}, $keys);

$params = array_combine($placeholders, $insert);

$query = sprintf('INSERT INTO `%s` (%s) VALUES (%s)',
    $table, implode(',', $cols), implode(',', $placeholders));

$stmt = $this->connection->prepare($query);
$stmt->execute($params);

答案 1 :(得分:1)

你应该单独绑定每个变量,bind_param将接受许多要绑定的变量:

$array = array('one' => $one, 'two' => $two);
$query = $sql->prepare("INSERT INTO `table` VALUES (?, ?)");
$query->bind_param('ss', $array['one'], $array['two']);
$query->execute();
// inserted