0

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 ?

AymDev
  • 6,626
  • 4
  • 29
  • 52
davimdantas
  • 123
  • 1
  • 8

1 Answers1

1

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.

user3783243
  • 5,368
  • 5
  • 22
  • 41
  • I'm ussing PDO and I'm passing $parameters to the execute function, you are right. But I still didn't get how it get by the `:name` that it is the value, not the key. – davimdantas Aug 28 '18 at 18:15
  • It is the key of the array. `['name' => $_POST['name']` so `:name` is replaced with `$_POST['name']`'s value and escaped. The `:` is optional for the array's index. If not present PDO auto adds it. – user3783243 Aug 28 '18 at 19:24
  • Here's another thread on the topic https://stackoverflow.com/a/38925175/3783243, see the section that starts with `This means that the parser can safely assume` – user3783243 Aug 28 '18 at 20:55
  • It's almost clear now, I'll take it for grant that in this structure the colons will indicate to replace for the value of that corresponded key, in this case `$_POST['name']`. – davimdantas Aug 29 '18 at 11:27
  • 1
    You can prove the theory by breaking it, add an `s` to one of the keys and you should get an error about the number of parameters/placeholders. – user3783243 Aug 29 '18 at 12:50
  • It really helped. – davimdantas Aug 29 '18 at 12:56