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.

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

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿