【问题标题】:Using PDO to insert data into database使用 PDO 将数据插入数据库
【发布时间】:2014-08-28 05:43:05
【问题描述】:

我正在尝试使用 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

?>

【问题讨论】:

    标签: php mysql sql pdo insert


    【解决方案1】:

    替换这个:

    $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-&gt;bindParam

    【讨论】:

    • 感谢您的回答,我现在正在使用第一个选项,它就像一个魅力!
    【解决方案2】:
      try{
            $stmt = null;               
            $stmt = $conn->prepare("INSERT INTO mst_finish (id, title, year, text) VALUES (:title, ':year', :text)");       
            $data = array(              
                ':title' => ucwords($_REQUEST['title']),
                ':year' => strtoupper($_REQUEST['year']),
                ':text' => $_REQUEST['text']);
            $stmt->execute($data);
            $_SESSION['_msg'] = "Finish succesfully saved..!";
         }
         catch (Exception $e)
         {      
            $str= filter_var($e->getMessage(), FILTER_SANITIZE_STRING);         
            $_SESSION['_msg_err'] = $str;           
         }
    

    【讨论】:

      猜你喜欢
      • 2014-04-17
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      • 2016-09-11
      • 2018-08-01
      • 1970-01-01
      相关资源
      最近更新 更多