dongzhan8620 2014-07-07 16: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:

<html>
<body>

<form name="blog post" action="insert.php" method="post">

<label for "id">Id: </label>
<input type="text" name="id">
<br>    
<label for "title">Title: </label>
<input type="text" name="title">
<br>    
<label for "year">Year: </label>
<input type="text" name="year">
<br>    
<label for "text">Text: </label>
<textarea rows="10" cols="50" name="text"></textarea>
<br>    
<button type="submit">Submit</button>
</form>

</body>
</html>

My insert.php code:

<?php

$pdo = new PDO('mysql:host=localhost;dbname=dbexample', 'userexample', 'paswexample', array(\PDO::MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8;SET time_zone = 'Europe/London'"));

$sql = "INSERT INTO `tableexample` (id, title, year, text)
                                        VALUES (:id, :title, :year, :text)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$stmt->bindParam(":title", $title);
$stmt->bindParam(":year", $year);
$stmt->bindParam(":text", $text);

$form = $_POST;
$id = $form[ 'id' ];                    
$title= $form[ 'title' ];                   
$year= $form[ 'year' ];                 
$text= $form[ 'text' ];                 


$stmt->execute();

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

if($result) {
    echo "Your text has been posted";

    }// end if
else {
    echo '0 results';
    }// end else

?>
  • 写回答

2条回答 默认 最新

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

    Replace this:

    $stmt->execute();
    
    $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条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵