Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jollyjaywhiskers's avatar

Could someone explain how this works? - PHP Practitioner Episode 20

I haven't got any problems with my code at the moment, but I can't quite grasp how it actually works.

In our QueryBuilder.php file, we create an insert method with 2 parameters "$table" and "$parameters". I get why "$table" works as we assign it to the 'users' table in the add-name.php file, but how does the text in the form get submitted to the database via the $parameters param? I'm not exactly following the logic so well and I just want to fully understand what's happening here.

For those of you who haven't watched the series and have no idea what I'm talking about, here's the snippet from the QueryBuilder.php file:

public function insert($table, $parameters)
    {
        $sql = sprintf(
         'INSERT INTO %s(%s) values (%s)', 
         $table, 
         implode(', ', array_keys($parameters)),
         ':' .implode(', :', array_keys($parameters))
        );

        try{
        $statement = $this->pdo->prepare($sql);
        $statement->execute($parameters);
        
    } catch (Exception $e){
            die($e->getMessage());
        }
    }

and here's the add-name.php file:

<?php

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

header('Location: /laracasts/PHP');
0 likes
1 reply
STEREOH's avatar

It is SQL parameter binding.

Basically this code :

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

will produce a string like this :

INSERT INTO users(name, etc...) values (:name, :etc...)'

Preparing this statement with pdo , you will tell it to wait for an array with a key of name.

Then you execute passing your parameter array wich happens to have a key of name.

So it will bind the value of the key nameto the :name in the request.

Please or to participate in this conversation.