【问题标题】:PDO not inserting into database but has correct valuesPDO 未插入数据库但具有正确的值
【发布时间】:2013-05-05 09:51:05
【问题描述】:

我正在尝试创建一个基本博客,并且我完全按照以前项目的语法插入到 mysql 数据库中,但这不会添加。我回显了这些值以查看它是否正确传递它,但是当我检查我的数据库时,没有添加任何内容。任何人都可以通过我的代码看到有什么问题吗?提前感谢任何回答的人,无论您是否能够提供帮助。

编辑:我还检查了我的数据库,它工作正常并且命名为,connect.php 也适用于我的登录,所以由于信息相同,它应该在这里工作。

edit2:数据库表如下

postid int(10) auto_increment 

title    text

author   text

date     date

content  text

tag1     text

tag2     text

<?php

// Make sure the user is logged in
session_name('blog');
session_start();
if (empty($_SESSION['username']))
{
    header("Location: loginhome.php");
    exit;
}

// Connect to the database and add a message
include("connect.php"); 

$one = $_POST['title'];
$two = $_POST['author'];
$three = $_POST['content'];
$four = $_POST['cat1'];
$five = $_POST['cat2'];
echo $two;


$add_message_query = $db->prepare("
    INSERT INTO `blogposts`
        (`title`, `author`, `date`, `content`, `tag1`, `tag2`)
    VALUES
        (:title, :author, CURRENT_TIMESTAMP, :content, :cat1, :cat2)
    ");

$add_message_query->execute(
    array(
    ':author' => $one,
    ':title' => $two,
    ':content' => $three,
    ':cat1' => $four,
    ':cat2' => $five
    )
);
//go to home to show new post
//header("Location: home.php");
?>   

【问题讨论】:

  • var_dump($db-&gt;ErrorInfo())var_dump($add_message_query-&gt;ErrorInfo()) 有什么用?
  • 您注意到您将$_POST['title'] 插入为:author 吗?此外,在标题和作者等少于 500 个字符的字段中,我个人更喜欢 NOW() 而不是 CURRENT_TIMESTAMPvarchar 而不是 text
  • asfasfsarray(3) { [0]=> string(5) "23000" [1]=> int(1048) [2]=> string(28) "列 'tag1' 不能null" } 是我做 var_dump($add_message_query->ErrorInfo()) 时发布的内容,我没有看到我切换了非常感谢你
  • @Chris 看来你对$_POST['cat1'] 没有任何价值。你也尝试过 var_dump() 吗?
  • 谢谢托熊。我之前在页面上的 html 中混淆了我的 id 和 name。感谢大家的帮助。

标签: php mysql pdo


【解决方案1】:

请使用$db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 以获得更好的错误处理。

http://www.php.net/manual/en/pdo.setattribute.php

【讨论】:

    猜你喜欢
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多