如何获取最后一个插入ID
INSERT INTO `cscart_static_data` ( `param_id` , `param` , `param_2` , `param_3` ,
`param_4` , `param_5` , `section` , `status` , `position` , `parent_id` , `id_path` ,
`localization` , `company_id` )
VALUES ('','index.php?dispatch=postview.view', '', '', '', '1', 'A', 'A', '0',
'0', '152', '', '1' );
INSERT INTO `cscart_static_data_descriptions` ( `param_id` , `lang_code` , `descr` )
VALUES ( SELECT LAST_INSERT_ID(), 'en', 'Blog' );
此处,第二个查询对我不起作用,因为 'SELECT LAST_INSERT_ID()'
为空。如何解决
答案 0 :(得分:1)
$sql = INSERT INTO `cscart_static_data` ( `param_id` , `param` , `param_2` , `param_3` , `param_4` , `param_5` , `section` , `status` , `position` , `parent_id` , `id_path` , `localization` , `company_id` ) VALUES ('','index.php?dispatch=postview.view', '', '', '', '1', 'A', 'A', '0', '0', '152', '', '1' );
mysql_query($sql);
$last_insert_id = mysql_insert_id();
现在在您的选择查询中使用此“ $ last_insert_id ”
答案 1 :(得分:0)
在PHP语言中,有一个函数可用,即mysqli_insert_id()。借助此函数,您可以从表中获取最后插入的id。
<!DOCTYPE html>
<html>
<body>
<?php
$con = mysqli_connect('localhost', 'root', '','test');
//$db = mysqli_select_db('test', $con);
echo 'Date = '.date('Y-M-d H:i:s')."<br/>";
$sql = "INSERT INTO `sample`(`name`, `address`, `date`) VALUES ('Pabitra','Kolkata'," . strtotime(date('Y-M-d H:i:s')) . ")";
echo $sql;
if (mysqli_query($con,$sql)) {
echo "Insert successfully";
}else{
echo 'error eccured.';
}
?>
<?php
$id = mysqli_insert_id($con);
$sql = "select * from sample where id = ".$id;
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
print_r($row);
$myXMLData = "<?xml version='1.0' encoding='UTF-8'?>
<note>
<id>".$id."</id>
<name>".$row['name']."</name>
<address>".$row['address']."</address>
<date>".date('Y-M-d H:i:s',strtotime($row['date']))."</date>
</note>";
$xml = simplexml_load_string($myXMLData) or die("Error: Cannot create object");
print_r($xml);
?>
</body>
答案 2 :(得分:0)
试试这个..
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
<强>参考:强>