-1

我使用以下代码通过 php pdo(来自一个类)将数据插入到 mysql 中:

$this->pdo = $this->connectMySql();
        if(isset($params['content'])){
            $query = 'INSERT INTO pages SET menu_name = :menu_name, position = :position, visible = :visible, content = :content, pagetype = :pagetype';
        }else{
            $query = 'INSERT INTO pages SET menu_name = :menu_name, position = :position, visible = :visible, pagetype = :pagetype';
        }
        $stmt = $this->pdo->prepare($query);
        $stmt->bindParam(':menu_name',$params['menu_name'], PDO::PARAM_STR);  // PDO::PARAM_STR is used for treating 
        $stmt->bindParam(':position',$params['position'], PDO::PARAM_INT);
        $stmt->bindParam(':visible',$params['visible'], PDO::PARAM_INT);
        if(isset($params['content'])){
            $stmt->bindParam(':content',$params['content'], PDO::PARAM_STR);
        }else{}
        $stmt->bindParam(':pagetype',$params['pagetype'], PDO::PARAM_STR);
        if(!$stmt->execute()){
            return false;
        }
        $lastid = $this->pdo->lastInsertId();
        $this->pdo = null;
        return $lastid;

它位于 try catch 块内。插入有效,但我想插入最后一个 id,我使用了以下(你可以在这里看到它的一部分),但是在 index.php 页面上我似乎没有得到 id:

$params = array(
            'menu_name' => $_POST['menu_name'],
            'position' => $_POST['position'],
            'visible' => $_POST['visible'],
            'content' => $_POST['editor1'],
            'pagetype' => $_POST['pagetype']
            );
if ($pages->insertPage($params)) {
    $html->redirect_to("content.php?pageid=" . $pages->lastid);
}else{
    $message = "Aanmaken van pagina is niet gelukt!";
}

任何帮助,将不胜感激。

我不明白为什么这是重复的。我已经看到了另一个问题,但那是关于将 lastinsertid 存储到数据库中(甚至可能不在一个类中)。
在我的主页(index.php)上,我调用了一个插入函数(来自一个类),当插入它时,它应该将 id 返回到主页。我什至尝试从另一篇文章中更改代码(以获取并返回 lastinsertid),但我得到的只是一个空值。

4

1 回答 1

-1

你调用 lastid 就像它是一种方法一样,在 index.php:9 我认为 $pages->lastid 会更好

于 2013-02-26T22:36:07.053 回答