Mar*_*nix 14 php database pdo lastinsertid
我有一个插入查询,我想从表中获取ID.我一直在搜索,我找到了PDO的lastInsertId().当我想使用它时,我得到PHP错误.
这是我的代码:
$db = new database();
$naam = $db->quoteQuery($_POST['naam']);
$barcode = $db->quoteQuery($_POST['barcode']);
$sql = "INSERT INTO products(name, barcode) VALUES (".$name.",".$barcode.")";
$results = $db->executeQuery($sql);
$lastid = $results->lastInsertId();
Run Code Online (Sandbox Code Playgroud)
但这给出了一个错误,这个错误:
Fatal error: Call to undefined method PDOStatement::lastInsertId() in /home/onlineweuh/domains/onlinewebapps.nl/public_html/vsb/admin/add-product.class.php on line 297
Run Code Online (Sandbox Code Playgroud)
我的数据库类:
class database
{
private $handleDB;
public function __construct()
{
$host = ;
$user = ;
$database = ;
$password = ;
try
{
$this->handleDB = new PDO('mysql:host='.$host.';dbname='.$database, $user, $password);
}
catch (PDOException $e)
{
print_r($e);
}
$this->handleDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
Run Code Online (Sandbox Code Playgroud)
我希望有人可以帮我解决它,我想要插入Query时给出的ID.
Dam*_*orn 30
您从PDO对象获取lastinsertid而不是结果对象.
尝试 $db->lastInsertId()
编辑如下.
您的数据库类封装了handleDB/PDO对象.由于handleDB变量是私有的,因此您无法在类外部访问它.您需要将其公之于众;
class database
{
public $handleDB;
public function __construct()
{
$host = 'removed';
$user = 'removed';
$database = 'removed';
$password = 'removed';
try
{
$this->handleDB = new PDO('mysql:host='.$host.';dbname='.$database, $user, $password);
}
catch (PDOException $e)
{
print_r($e);
}
$this->handleDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以打电话了 $db->handleDB->lastInsertId();
或者您可以将其公开为handleDB->lastInsertId()如下函数:
class database
{
private $handleDB;
public function __construct()
{
$host = 'remove';
$user = 'removed';
$database = 'removed';
$password = 'removed';
try
{
$this->handleDB = new PDO('mysql:host='.$host.';dbname='.$database, $user, $password);
}
catch (PDOException $e)
{
print_r($e);
}
$this->handleDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
public function lastInsertId(){
return $this->handleDB->lastInsertId();
}
}
Run Code Online (Sandbox Code Playgroud)
你会打电话使用 $db->lastInsertId();
dec*_*eze 13
lastInsertId是一种方法PDO,而不是PDOStatement.因此:
$db->lastInsertId();
Run Code Online (Sandbox Code Playgroud)