A
A
Andrey Elsukov2020-05-21 09:42:46
PHP
Andrey Elsukov, 2020-05-21 09:42:46

PDO code to embed?

Just learning php
I found a source with this code to insert into a table: I
need your help to understand this code

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


continuation:
$allowed = array("name","surname","email"); // allowed fields
$sql = "INSERT INTO users SET ".pdoSet($allowed,$values);
$stm = $dbh->prepare($sql);
$stm->execute($values);


before that I was able to do an insert with variables through mysql. Now I'm trying to improve my level. But then I got a little stuck)
Thank you in advance for your answer)

PS Link to the source phpfaq.ru/pdo#fetchall

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2020-05-21
@Dropsen

Let's start with the fact that this is an automated embed code.
And first you need to learn how to insert manually.
Everything is done manually

$sql = "INSERT INTO users (name, surname, sex) VALUES (?,?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$name, $surname, $sex]);

First we replace all the variables in the query with question marks
Then we do prepare this query
And then we do execute, passing the variables to insert as an array
Got it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question