首页 > 解决方案 > How a placeholder in a prepared statement calls a value in an associative array?

问题描述

The code is already working, but I couldn't fully understand how the place-holders is calling the value of an associative array. I already read the documentation but without success to understand it.

$app['dtb'] -> insert('users', [
    'name' => $_POST['name']
    'age' => $_POST['age],  ]);`

My insert method:

$sql = sprintf(
    'insert into %s (%s) values (%s)',
    $table,
    implode(', ' , array_keys($parameters)),
    ':' . implode(', :' , array_keys($parameters))
);

So this would result on something like this:

insert into users (name) values (:name)

If i'm not using any bind_param how it identify that :name is the value of the key name ?

标签: phpprepared-statementassociative-arrayplaceholder

解决方案


bind_param is a mysqli function. That driver does not support named placeholders. You must be using PDO, PDO has a bindparam function that is similar. It also allows you to just pass an array to the execute function. This binds the values in the order they appear if unnamed placeholders were used (?), or by the keys of the array if the placeholders were named (:...). I'd guess you are passing $parameters to the execute function.


推荐阅读