1

可以说我有这个代码:

$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 对象

4

2 回答 2

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);
于 2013-10-16T02:12:20.153 回答
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
于 2013-10-16T00:45:10.537 回答