简体   繁体   English

pdo 包装器最后一个 ID 返回 0

[英]pdo wrapper last id return 0

hello Iam trying to make a project using php mvc and I used on it pdo wrapper package the main problem that when I use lastinsertid it always return 0 I know that I should use the same connection but in my case with the package how can I do it??你好,我正在尝试使用 php mvc 创建一个项目,我在它上面使用了 pdo 包装器 package 主要问题是当我使用 lastinsertid 它总是返回 0 我知道我应该使用相同的连接但在我的情况下使用 package 我该怎么做它??

this is the model code这是 model 代码

<?php
   namespace MVC\core;
    use Dcblogdev\PdoWrapper\Database as Database;

    class model{
   static function db(){
    $options = [
    //required
    'username' => 'root',
    'database' => 'gallery',
    //optional
    'password' => '',
    'type' => 'mysql',
    'charset' => 'utf8',
    'host' => 'localhost',
    'port' => '3306'
     ];
      return  $db = new Database($options);
    }
    }
    ?>

and here where I use the pdo with my function在这里,我将 pdo 与我的 function 一起使用

    <?php
namespace MVC\model;
use MVC\core\model;
use MVC\core\session;
class adminpost extends model {
function getCategory(){
    return  model::db()->rows("SELECT * FROM `category` WHERE id NOT in (SELECT parent_id from category)");
}
function getposts(){
    return  model::db()->rows("select * from posts");
}
function getpostsByCategory($id){
    return  model::db()->rows("select * from posts where category_id = ?",[$id]);
}
function insertimage($data){
    return model::db()->insert('images', $data);

}
function insertpost($data){
     return model::db()->insert('posts', $data);

}
function lastid(){
    return model::db()->lastInsertId();

}
}


?>

and here is the controller where I use the model function这是 controller,我使用 model function

class adminpostcontroller extends controller{
function postinsert(){
$post = new adminpost;
$data = [
'title'=>$_POST['title'],
'text'=>$_POST['text']
];
$insert = $post->insertpost($data);
}
}

I'm assuming its that every time you call model::db() you're establishing a new connection due to new Database($options) , you need to create and retain one connection for the duration of your actions via a static reference or another most appropriate means.我假设每次调用model::db()时,由于new Database($options)都会建立一个新连接,您需要通过 static 参考在操作期间创建并保留一个连接或其他最合适的方式。

A "cheap" way to do this is一种“便宜”的方法是

static $db;
return isset( $db ) ? $db : $db = new Database($options);

Other ways could be to create a reference in your class like static $db;其他方法可能是在您的 class 中创建一个引用,例如static $db; and use static::$db并使用static::$db

class model{
  static $db;

followed by其次是

return isset( static::$db ) ? static::$db : static::$db = new Database($options);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM