【问题标题】:Auto increment ID not being correclty assigned in SQL database by PHPPHP未在SQL数据库中正确分配自动增量ID
【发布时间】:2014-10-11 12:10:07
【问题描述】:

我很困惑。我正在设计的新 CMS 中出现了一些问题。我正在关注本教程,但正在更改一些内容(包括使用 SQLite 而不是 MySQL)并添加更多功能。 http://www.elated.com/articles/cms-in-an-afternoon-php-mysql/

无论如何,现在几乎所有东西都可以正常工作,但它不会保存新帖子。不过,编辑帖子功能确实有效。

这是基本表单(与编辑帖子相同的表单):

<h3>Create a blog post</h3>
<form method="POST" action="index.php?action=<?php echo $posts['formAction']; ?>">
     <input type="hidden" id="id" name="id" value="<?php echo $posts['post'] -> id; ?>" />
     <p>Title: <input id="title" name="title" type="text" placeholder="Enter the post title" required autofocus maxlength="255" value="<?php echo $posts['post'] -> title; ?>"/></p>
     <p>Category: <input id="category" name="category" type="text" placeholder="Enter the post category" required maxlength="255" value="<?php echo $posts['post'] -> category; ?>"/></p>
     <p>Tags: <input id="tags" name="tags" type="text" placeholder="Enter some tags for the post" required value="<?php echo $posts['post'] -> tags; ?>"/></p>
     <p>Summary:</p><textarea id="summary" name="summary" cols="100" rows="5" placeholder="Enter a short summary of the post's content" required><?php echo $posts['post'] -> summary; ?></textarea>
     <p>Content:</p><textarea id="body" name="body" cols="100" rows="30" placeholder="Enter the main content of the post" required><?php echo $posts['post'] -> body; ?></textarea>
     <p>Publication date: </p><input type="date" id="pubDate" name="pubDate" placeholder="DD-MM-YYYY" required maxlength="10" value="<?php echo $posts['post'] -> pubDate ? date('Y-m-d', $posts['post'] -> pubDate) : ''; ?>" />
     <br />
     <input id="saveChanges" name="saveChanges" type="submit" value="Create Post"/>
</form>

这最终发布到 index.php 中的以下函数:

function newPost()
{
    $posts = array();
    $posts['formAction'] = "newPost";

    if (isset($_POST['saveChanges']))
    {
        $post = new Post;
        $post -> storePostValues($_POST);
        $post -> insertPost();
        header("Location: index.php?status=changesSaved");
    }
    elseif (isset($_POST['cancel']))
    {
        header('Location: index.php');
    }
    else
    {
        $posts['post'] = new Post;
        require('editPost.php');
    }
}

最后是 Post() 类中的相关代码:

public function __construct($data = array()) {
    if (isset($data['id'])) $this -> id = (int) $data['id'];
    if (isset($data['title'])) $this -> title = $data['title'];
    if (isset($data['pubDate'])) $this -> pubDate = (int) $data['pubDate'];
    if (isset($data['reviseDate'])) $this -> reviseDate = (int) $data['reviseDate'];
    if (isset($data['category'])) $this -> category = $data['category'];
    if (isset($data['tags'])) $this -> tags = $data['tags'];
    if (isset($data['summary'])) $this -> summary = $data['summary'];
    if (isset($data['body'])) $this -> body = $data['body'];
    if (isset($data['views'])) $this -> views = (int) $data['views'];
    if (isset($data['likes'])) $this -> likes = (int) $data['likes'];
    if (isset($data['dislikes'])) $this -> dislikes = (int) $data['dislikes'];
}

        //Sets object properties from form POST values
public function storePostValues($params) {
    $this -> __construct($params);

    if (isset($params['pubDate'])) {
        $pubDate = explode('-', $params['pubDate']);
        if (count($pubDate) == 3) {
            list ($d, $m, $y) = $pubDate;
            $this -> pubDate = mktime(0, 0, 0, $m, $d, $y);
        }
    }
    if (isset($params['reviseDate'])) {
        $reviseDate = explode('-', $params['reviseDate']);
        if (count($reviseDate) == 3) {
            list ($d, $m, $y) = $reviseDate;
            $this -> reviseDate = mktime(0, 0, 0, $m, $d, $y);
        }
    }
}

public function insertPost() {
    if (!is_null($this -> id)) trigger_error("Post::insertPost(): Post ID already assigned.", E_USER_ERROR);
    $dblocat = "sqlite:" . $_SERVER['DOCUMENT_ROOT'] . "/cgi-bin/blog.db";
    $dbcon = new PDO($dblocat);
    $dbcon->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $sqlstr = "INSERT INTO posts(title, pubDate, reviseDate, category, tags, summary, body, views, likes, dislikes) VALUES(:title, FROM_UNIXTIME(:pubDate), FROM_UNIXTIME(:reviseDate), :category, :tags, :summary, :body, :views, :likes, :dislikes)";
    $preparedstr = $dbcon -> prepare($sqlstr);
    $preparedstr -> bindValue(":title", $this -> title, PDO::PARAM_STR);
    $preparedstr -> bindValue(":pubDate", $this -> pubDate, PDO::PARAM_INT);
    $preparedstr -> bindValue(":reviseDate", $this -> reviseDate, PDO::PARAM_INT);
    $preparedstr -> bindValue(":category", $this -> category, PDO::PARAM_STR);
    $preparedstr -> bindValue(":tags", $this -> tags, PDO::PARAM_STR);
    $preparedstr -> bindValue(":summary", $this -> summary, PDO::PARAM_STR);
    $preparedstr -> bindValue(":body", $this -> body, PDO::PARAM_STR);
    $preparedstr -> bindValue(":views", 0, PDO::PARAM_INT);
    $preparedstr -> bindValue(":likes", 0, PDO::PARAM_INT);
    $preparedstr -> bindValue(":dislikes", 0, PDO::PARAM_INT);
    $preparedstr -> execute();
    $this -> id = $dbcon -> lastInsertId();
    $dbcon = null;
}

那么会发生什么?好吧,每次我保存帖子时,都会触发 insertPost() 函数中的错误,说帖子 ID 已经存在……但它在数据库中设置为自动递增,所以我不太确定发生了什么。 .. 我对 PHP 比较陌生,现在花了几个小时试图看看为什么这不起作用。

任何建议都将不胜感激,如果需要,我可以发送更多代码。 同样,我将它基于本教程,但我已经对其进行了修改,现在使用 SQLite。 http://www.elated.com/articles/cms-in-an-afternoon-php-mysql/

提前致谢, 伊尔蒙

【问题讨论】:

    标签: php sql database sqlite content-management-system


    【解决方案1】:

    您只需删除此行即可使其正常工作(在您的函数 __construct() 中)

    if (isset($data['id'])) $this -> id = (int) $data['id'];
    

    id 设置为“自动递增”,所以这意味着你不应该提供任何 id(数据库会为你选择一个)。

    编辑:

    其实你应该把这条线放在这里。 正如您所注意到的,删除它会阻止您获取帖子 ID。

    这是我的看法: 当你创建一个新帖子时,你应该有几行这样的:

    // User has posted the article edit form: save the new article
    $post = new Post;
    $post->storeFormValues( $_POST );
    $post->insert();
    

    对吗? 现在如何在“插入”之前添加这个未设置的语句:

    // User has posted the article edit form: save the new article
    $post = new Post;
    $post->storeFormValues( $_POST );
    unset($post->id);
    $post->insert();
    

    (您可能需要根据您的代码调整变量名称)

    【讨论】:

    • 这可行,但现在它似乎不再在我的 getPosts() 函数中从数据库中检索主键“id”列,尽管指定 ID 的 getPostByID($id) 确实有效。这意味着我从主页使用 href="viewPost.php?postID= id;?>" 的链接不起作用......但是像 $post -> title 这样的东西却不是不再检索该列。建议?
    • 我对此有一个想法。您可以编辑您的帖子并添加您的函数 insert() 的代码,以便我可以提供帮助吗?
    • 非常感谢;据我所知,您对取消设置帖子 ID 的修改使一切正常。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-10-09
    • 2012-03-10
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 2015-07-05
    • 2020-06-14
    相关资源
    最近更新 更多