zero50x

PDO подключение + вставка

Oct 10th, 2021 (edited)
1,298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.18 KB | None | 0 0
  1. $today = date("Y-m-d");
  2.  
  3.  
  4. try {
  5.     $dbh = new PDO('mysql:dbname=NAME;  host=localhost', 'USER', 'PASSWORD');
  6. } catch (PDOException $e) {
  7.     die($e->getMessage());
  8. }
  9.  
  10.  
  11. $sth = $dbh->prepare("INSERT INTO `main` SET
  12.     `tel` = :tel,
  13.     `mail` = :mail,
  14.     `theme_first` = :themef,
  15.     `theme_second` = :themes,
  16.     `dateadd` = :dateadd"
  17. );
  18.  
  19. $sth->execute(array(
  20.     'tel' => '788888888888',
  21.     'mail' => 'xxxx@mail.ru',
  22.     'themef' => 'Автосервис',
  23.     'themes' => 'Кузовные',
  24.     'dateadd' => $today
  25. ));
  26.  
  27. $insert_id = $dbh->lastInsertId();
  28. echo 'insert_id <pre>'; var_dump($insert_id); echo '</pre>';
  29.  
  30.  
  31.  
  32. // Так работает только с переменными потому что bindParam:
  33. $tel = '798887776655';
  34.  
  35. $b=$pdo->prepare(" INSERT INTO `main` SET tel=:tel");
  36. $b->bindParam(":tel", $tel);
  37. $b->execute();
  38. $LastId = $pdo->lastInsertId();
  39.  
  40. // А так будет ошибка
  41. $b->bindParam(":tel", '798887776655');
  42.  
  43. // А так будет работать и со значениями потому что bindValue:
  44. $b=$pdo->prepare(" INSERT INTO `main` SET tel=:tel");
  45. $b->bindValue(":tel", '7333344455');
  46. $b->execute();
  47. $LastId2 = $pdo->lastInsertId();
  48.  
  49.  
  50.  
Add Comment
Please, Sign In to add comment