php - 使用PDO向数据库中插入数据

标签 php mysql sql pdo insert

我正在尝试使用 PDO 将数据插入我的数据库,但我收到错误“0 个结果”。我已经使用 PDO 从我的数据库中选择数据,但这是我第一次使用它来插入数据,因此对以下代码的任何帮助将不胜感激!

我的表单:

<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>

我的 insert.php 代码:

<?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

?>

最佳答案

替换这个:

$stmt->execute();

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

用这个:

$result = $stmt->execute();

或...仅使用:

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

并移除所有的$stmt->bindParam

关于php - 使用PDO向数据库中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24615721/

相关文章:

javascript - 使用托管字段时如何处理现有客户付款方式?

php - MySQL 将多个列中的唯一项目分组,每个列有 COUNT 个?

PHP 选择所有数据及其所有子数据(嵌套查询)

mysql - fetchRow() Zend Framework 中的简单 SQL 语法错误

php - 跟踪访问者最后查看的项目

java - 使用 INNER JOIN 查询

php - 带有别名的 SUM() 字段上的 Doctrine orderBy

php - 如果字段内容是搜索字符串的一部分,mysql如何设置 "where"条件?

mysql - 是否可以按索引命名列

mysql - 替换特定表中每一列中的字符串