如何从类中将最后插入的ID转换为重定向

时间:2013-02-26 22:14:05

标签: php mysql pdo lastinsertid

我使用以下代码将数据插入到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),但我得到的只是一个空值。

1 个答案:

答案 0 :(得分:-1)

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