Advertisement
Guest User

Minimal script for inserting date into mysql using bind variables

a guest
Jan 13th, 2021
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.82 KB | None | 0 0
  1. <?php
  2. /*
  3. CREATE DATABASE talin;
  4. USE talin;
  5. CREATE TABLE t2 (a varchar(8), b date, c int);
  6. */
  7.   function db_error($action, $error) {
  8.     printf("%s failed: %s\n", $action, $error);
  9.     exit();
  10.   }
  11.  
  12.   $timestamp = DateTime::createFromFormat('d/m/Y','1/1/2021');
  13.   $iso_date = $timestamp->format('Y-m-d');
  14.  
  15.   $db = new mysqli('localhost', 'talin', 'talin_password', 'talin');
  16.   if(mysqli_connect_errno())
  17.     db_error('Connect', $db->error);
  18.  
  19.   $query = "INSERT INTO t1(a, b, c) VALUES(?, ?, ?)";
  20.   $stmt = $db->prepare($query);
  21.   if(!$stmt)
  22.     db_error('Prepare', $db->error);
  23.  
  24.   $a = 'text';
  25.   $b = $iso_date;
  26.   $c = 0;
  27.   $bound = $stmt->bind_param('ssi', $a, $b, $c);
  28.   if(!$bound)
  29.     db_error('Bind', $db->error);
  30.  
  31.   $executed = $stmt->execute();
  32.   if(!$executed)
  33.     db_error('Execute', $db->error);
  34. ?>
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement