PDO bindParam into one statement?

前端 未结 5 1800
刺人心
刺人心 2020-12-02 19:14

Is there a way I can put these bindParam statements into one statement?

$q = $dbc -> prepare(\"INSERT INTO accounts (username, email, password) VALUES (:u         


        
5条回答
  •  借酒劲吻你
    2020-12-02 19:53

    helper function is a function that makes you help to avoid writing bunch of repetitive code every time you want to run a query.
    This is called "programming" and there is almost none of it on this site, at least under "PHP" tag.
    While many peiople thinks that programming stands for copy/pasting chunks of code from manual examples, it's somewhat different. Although it's hard to learn but really worth it, especially if you're devoting yourself to web-developing.

    As you can see, no accepted answer did no real help for you, as you still have to write something like

    $sth->execute(array(':username' => $_POST['username'], 
                        ':email' => $_POST['email']
                        ':password' => $_POST['password']);
    

    as many times as many fields in your table, which makes not much difference from your initial approach, still makes you write each field name FOUR times.

    But being a programmer, you can use powers of programming. A loop, for example - one of cornerstone programming operators.
    Every time you see repetitions, you know there should be a loop.

    for example, you can set up a list of fields, naming them only once. And let a program do the rest.

    Say, such a function like this one

    function pdoSet($fields, &$values, $source = array()) {
      $set = '';
      $values = array();
      if (!$source) $source = &$_POST;
      foreach ($fields as $field) {
        if (isset($source[$field])) {
          $set.="`$field`=:$field, ";
          $values[$field] = $source[$field];
        }
      }
      return substr($set, 0, -2); 
    }
    

    being given an array of field names, it can produce both insert statement and data array for you. Programmatically. So, your code become no more than these 3 short lines:

    $fields = array('username', 'email', 'password');
    $stmt = $dbh->prepare("INSERT INTO accounts SET ".pdoSet($fields,$values));
    $stmt->execute($values);
    

提交回复
热议问题