PDO lastInsertId()没有得到值

时间:2012-11-17 13:18:59

标签: php mysql pdo

我无法使用$db->lastInsertId();$db->lastInsertId('fid');

获取lastinsertid值
$stmt = $db->stmt_init();   

$sql = "INSERT INTO ch_files_details (name,extension,size,parent) VALUES (?,?,?,?)";

$stmt = $db->prepare($sql) or die($db->error());

$stmt->bind_param('ssii', $filename, $extension, $filesize, $parent);  

$stmt->execute();

$fid = $db->lastInsertId();

那里有什么遗漏或错误?

我能够插入到表格中但却无法获得最后插入的ID。

Table Definition: 
`ch_files_details` (
`fid` bigint(20) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`extension` text NOT NULL,
`size` bigint(20) NOT NULL,
`parent` bigint(20) NOT NULL,
PRIMARY KEY (`fid`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ;

1 个答案:

答案 0 :(得分:2)

PDO::lastInsertId在这里不起作用,因为您没有使用PDO 。上面的代码是MySQLi代码,而不是PDO。使用mysqli::$insert_id.

// This is all MySQLi prepared statement code, not PDO!!!
// PDO uses bindParam(), not bind_param(), doesn't have stmt_init(), and doesn't use the 'ssii' type strings for binding
$stmt = $db->stmt_init();   
$sql = "INSERT INTO ch_files_details (name,extension,size,parent) VALUES (?,?,?,?)";
$stmt = $db->prepare($sql) or die($db->error());
$stmt->bind_param('ssii', $filename, $extension, $filesize, $parent);  
$stmt->execute();

// insert_id is a property of the connection MySQLi object
$fid = $db->insert_id;

查看the MySQLi manual了解详情。在某些时候,你最终得到了错误的文档集。