doufan6886 2012-08-20 21:43
浏览 48
已采纳

通过PDO将数据插入MySQL,尝试使用数组包含时间戳和数据 - 获取错误?

I have a set of data stored in variables, and I want a page to write that data to a MySQL database, I'd like to include the time of insertion, here's my method:

$username="username"; $password="password";


try {
  $pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $stmt = $pdo->prepare('INSERT INTO table01
  (
   Time,
   variable1,
   variable2,
  )

VALUES
  (
    :Time,
    :variable1,
    :variable2,
  )');


  $stmt->execute(array(
        ':Time' => NOW(),
        ':variable1' => $var1,
        ':variable2' => $var2,
  ));

  echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}

On loading this page, the css is stripped from the page, I get a sort of garbled output of what the page should look like (white screen, plain text some images), additionally on checking the database nothing has been written to it.

Without the Time variable in there, all works perfectly.

Any advice? Thanks in advance

  • 写回答

1条回答 默认 最新

  • dongzhang1864 2012-08-20 21:46
    关注

    Sorry, took me moment to re-read that. You are using the nysql function now() to do the work, and as such you don't need to set it as a param and therefore don't need to bind it at all. Just write it into your query.

      $stmt = $pdo->prepare('INSERT INTO table01
      (
       Time,
       variable1,
       variable2,
      )
    
    VALUES
      (
        now(),
        :variable1,
        :variable2,
      )');
    
      $stmt->execute(array(
        ':variable1' => $var1,
        ':variable2' => $var2,
      ));
    

    Edit Re Comment

    The : in a query denotes it as a parameter in a prepared query. That means you must then bind it via the bind() command. However if you are inserting the data from within the database (such as using a built in function, or pulling the data in from another row) you don't need to declare it in the initial query with : and therefore you can't pass it to the query in the bound params array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失