Binding values within a function to INSERT INTO DB

杀马特。学长 韩版系。学妹 提交于 2021-01-29 04:25:43

问题


Lets say I have this code:

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

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.

edited:

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();
}

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


回答1:


Ok, here's how I would approach this with PDO (since OP asked)

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); 

Then, in your sql_insert_bind method

$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);



回答2:


You should bind each variable seperately, bind_param will accept many variables to bind:

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


来源:https://stackoverflow.com/questions/19393438/binding-values-within-a-function-to-insert-into-db

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!