dongzhan8620 2014-07-07 08:49
浏览 64
已采纳

使用PDO将数据插入数据库

I'm trying to use PDO to insert data into my database but I'm getting the error "0 results". I already used PDO to select data from my database but this is the first time I use it to insert data so any help with the below code would be appreciated!

My form:

  1. <html>
  2. <body>
  3. <form name="blog post" action="insert.php" method="post">
  4. <label for "id">Id: </label>
  5. <input type="text" name="id">
  6. <br>
  7. <label for "title">Title: </label>
  8. <input type="text" name="title">
  9. <br>
  10. <label for "year">Year: </label>
  11. <input type="text" name="year">
  12. <br>
  13. <label for "text">Text: </label>
  14. <textarea rows="10" cols="50" name="text"></textarea>
  15. <br>
  16. <button type="submit">Submit</button>
  17. </form>
  18. </body>
  19. </html>

My insert.php code:

  1. <?php
  2. $pdo = new PDO('mysql:host=localhost;dbname=dbexample', 'userexample', 'paswexample', array(\PDO::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8;SET time_zone = 'Europe/London'"));
  3. $sql = "INSERT INTO `tableexample` (id, title, year, text)
  4. VALUES (:id, :title, :year, :text)";
  5. $stmt = $pdo->prepare($sql);
  6. $stmt->bindParam(":id", $id);
  7. $stmt->bindParam(":title", $title);
  8. $stmt->bindParam(":year", $year);
  9. $stmt->bindParam(":text", $text);
  10. $form = $_POST;
  11. $id = $form[ 'id' ];
  12. $title= $form[ 'title' ];
  13. $year= $form[ 'year' ];
  14. $text= $form[ 'text' ];
  15. $stmt->execute();
  16. $result = $stmt->execute(array(':id'=>$id, ':title'=>$title, ':year'=>$year, ':text'=>$text));
  17. if($result) {
  18. echo "Your text has been posted";
  19. }// end if
  20. else {
  21. echo '0 results';
  22. }// end else
  23. ?>

展开全部

  • 写回答

2条回答 默认 最新

  • doufa5001 2014-07-07 08:52
    关注

    Replace this:

    1. $stmt->execute();
    2. $result = $stmt->execute(array(':id'=>$id, ':title'=>$title, ':year'=>$year, ':text'=>$text));

    with this:

    $result = $stmt->execute();
    

    or...use only:

    $result = $stmt->execute(array(':id'=>$id, ':title'=>$title, ':year'=>$year, ':text'=>$text));
    

    and remove all of $stmt->bindParam

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部