[英]getting a last inserted varchar id which is an primary key
I have multiple table ,which has to be inserted using different forms and all table have one id which is primary key and its varchar (NOT NULL),So i have one class function named as id_calc($tbl,$id) where $tbl is a parameter with table name and $id is a field id .And each time while inserting this function has to be called for id. 我有多个表,必须以不同的形式插入,所有表都有一个ID是主键及其varchar(非NULL),所以我有一个名为id_calc($ tbl,$ id)的类函数,其中$ tbl是具有表名的参数,$ id是字段id。每次插入该函数时,都必须为id调用此函数。
for example: If my id is "web1" ,next when i insert it shud give "web2","web3"...... i have tried with LAST_INSERT_ID() but its not working.so i tried with fetching the max(id) and splitting the string and variable but is also giving some problem.so how can i do this.please help!!! 例如:如果我的id是“ web1”,下一个当我插入它时应该给“ web2”,“ web3” ......我尝试使用LAST_INSERT_ID()但它不起作用。所以我尝试获取最大(ID)并拆分字符串和变量,但也给了一些问题。所以我该怎么做。请帮助!
class first{
public function id_calc($tbl,$id)
{
$sql = mysql_query("SELECT max($id) FROM $tbl where $id like '%web%'");
if($sql)
{
while ($row = mysql_fetch_assoc($sql))
{
$user=$row;
$a=implode(" ",$user);
}
$pattern = "/(\d+)/";
$array = preg_split($pattern, $a, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$new[]=$array['0'];
$new[]=$array['1']+1;
$result=implode("",$new);
return $result;
}
}
}
this function is called like 这个功能叫做
public function insertreport1()
{
$obj=new first();
$id=$obj->id_calc(tablename,idfield);
//insert query
}
this is my table structure 这是我的表结构
CREATE TABLE `report` (
`inc_id` varchar(25) NOT NULL,
`inc_status` int(11) NOT NULL,
`inc_date` datetime NOT NULL,
`inc_Name` varchar(45) NOT NULL,
`inc_Age` int(11) NOT NULL,
`inc_Gender` varchar(45) NOT NULL,
`inc_Mobile` varchar(45) NOT NULL,
`inc_Address` varchar(250) NOT NULL,
`inc_treatment` varchar(45) DEFAULT NULL,
`inc_userid` varchar(10) NOT NULL,
`inc_repTime` datetime NOT NULL
PRIMARY KEY (`inc_id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Pseudo implementation would be 伪实现将是
alter table definition 修改表定义
alter table `table` add column id int(11) not null auto_increment
change code 变更密码
public function id_calc($tbl,$idcol) {
$sql = mysql_query("SELECT id FROM $tbl order by id desc limit 1");
if($sql){
while($row = mysql_fetch_assoc($sql));
$id = isset($row['id']) ? $row['id'] + 1 : 1;
return "{$idcol}{$id}";
}
}
Hope this helps 希望这可以帮助
我认为您可以这样做。将查询写为“ SELECT MAX(CAST(SUBSTRING($ id,4,12)AS UNSIGNED))FROM $ tbl WHERE $ id Like'%web%'”,然后递增id为web +(max + 1)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.