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??
this is the model code
<?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
<?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
class adminpostcontroller extends controller{
function postinsert(){
$post = new adminpost;
$data = [
'title'=>$_POST['title'],
'text'=>$_POST['text']
];
$insert = $post->insertpost($data);
}
}
CodePudding user response:
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.
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;
and use static::$db
class model{
static $db;
followed by
return isset( static::$db ) ? static::$db : static::$db = new Database($options);