dscojuxf69080 2019-04-05 06:38
浏览 37

有人可以帮我理解为什么这段代码真的有用吗?

I've been following the Laracasts "PHP Practitioner" series to help me get a basic understanding of PHP and at this point, my code works fine and doesn't return any errors, but I can't quite grasp how it actually works.

If you've watched the series, in Episode 20, 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, we basically make a simple form with an input and a submit button and at this point, we are sending the info from the form into a DB. 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');
  • 写回答

1条回答 默认 最新

  • drpph80800 2019-04-05 06:48
    关注

    Please take a look at this https://www.php.net/manual/en/book.pdo.php

    PDO works in a way that allows you to define the query structure and then add your values to it. This is made in order to deny SQL injection.

    $statement = $this->pdo->prepare($sql);
    $statement->execute($parameters);
    

    In the first line you are preparing the query you defined, you tell PDO which kind of query you want to run. In the second line you actually run it, binding your parameters to the query.

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP