How to get the last insert 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' );
Here , the second query doesn't work for me, because 'SELECT LAST_INSERT_ID()'
is empty .How to solve
$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();
Now use this " $last_insert_id " in your select query
In PHP language a function is available and that is mysqli_insert_id(). By the help of this function you can fetch last inserted id from the table.
<!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>
Try this..
<?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());
?>
Reference:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.