插入 cookie 和日期 pdo mysql

Insert cookies and date pdo mysql

我尝试将 3 个 cookie 和带有 pdo 的日期插入到我的数据库中。但我不知道我该怎么做。输入值被插入到数据库中。并且之前在页面中设置了cookie。有什么提示吗?

<?php
  $cookie_name = 'longitude';
  if(isset($_POST["submit"])){

    $hostname='localhost';
    $user='root';
    $password='';
    $id = 'userid';
    $_COOKIE["$id"];
    $longitude = 'longitude';
    $_COOKIE["$longitude"];
    $latitude = 'latitude';
    $_COOKIE["$latitude"];
    $date = date('Y-m-d');

    try {
      $dbh = new PDO("mysql:host=$hostname;dbname=localy",$user,$password);
      $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
      $sql = "INSERT INTO post (title, text)
              VALUES ('".$_POST["title"]."' ,'".$_POST["text"]."')";

      if ($dbh->query($sql)) {
        echo "New Record Inserted Successfully";
      }
      else{
        echo "Data not successfully Inserted.";
      }

      $new = $dbh->lastInsertId();
      $dbh = null;
    }

    catch(PDOException $e)
    {
      echo $e->getMessage();
    }

    if ($new > 0 && $_POST["title"] && $_POST["text"]) {
      $message['success'] = 'Neuer Benutzer (' . htmlspecialchars($_POST['username']) . ') wurde angelegt, <a href="login.php">weiter zur Anmeldung</a>.';
      header('Location: http://' . $_SERVER['HTTP_HOST'] . '/loc/main.php');

    } 
    else {

    }
  }

?>

带有评论的概念证明

<?php

if (isset($_POST["submit"]) /* add validation such as title and text are not empty*/ ) {
    $user='root';
    $password='';

    // close all db code to try/catch
    try {
        $dbh = new PDO("mysql:host=localhost;dbname=localy", $user, $password);

        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
        // prepare your query
        $query = 'INSERT INTO post (title, text, userid, longitude, latitude, date) VALUES (?, ?, ?, ?, ?, CURRENT_DATE)';

        $stmt = $dbh->prepare($query);
        // bind variables
        $stmt->execute(array($_POST['title'], $_POST['text'], $_COOKIE['userid'], $_COOKIE['longitude'], $_COOKIE['latitude']));
        // pull last insert id
        $new = $dbh->lastInsertId(); 

        // show success message or redirect, whatever you want
        echo "New Record Inserted Successfully";
        $message['success'] = 'Neuer Benutzer (' . htmlspecialchars($_POST['username']) . ') wurde angelegt, <a href="login.php">weiter zur Anmeldung</a>.';
        //header('Location: http://' . $_SERVER['HTTP_HOST'] . '/loc/main.php');

    } catch(PDOException $e) {
        // if error show error message or redirect to error page...
        echo "Data not successfully Inserted.";
        echo $e->getMessage();
    }
}