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

Posted 2 months ago by jollyjaywhiskers

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

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.