将函数内的值绑定到INSERT INTO DB [英] Binding values within a function to INSERT INTO DB
问题描述
让我说我有这段代码:
$array = array('one' => $one, 'two' => $two);
$sql->sql_insert('table_name', $array);
我有类对象 $ sql
和函数 sql_insert
,但是我将如何使用mysqli准备的语句来绑定值并将其插入到db中呢?并说 mysqli连接
是 $ this->连接
I have the class object $sql
and the function sql_insert
but how would I use the mysqli prepared statements to bind the values and insert it into the db? And lets say the mysqli connection
is $this->connection
任何建议都将非常感谢.
Any advice would be great thanks.
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();
}
我收到错误消息:致命错误:在非对象上调用成员函数bind_param()
,但是 $ this-> connection
是mysqli对象
I get the error message: Fatal error: Call to a member function bind_param() on a non-object
but $this->connection
is the mysqli object
推荐答案
好的,这就是我要使用PDO处理此问题的方法(因为要求OP)
Ok, here's how I would approach this with PDO (since OP asked)
我假定您已将PDO对象作为 $ connection
属性实例化或注入到您的类中,例如
I'll assume you've instantiated or injected a PDO object into your class as the $connection
property, eg
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);
这篇关于将函数内的值绑定到INSERT INTO DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!