duan5731 2015-02-26 10:05
浏览 191
已采纳

获取最后插入的varchar id是主键

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.

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!!!

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;
  • 写回答

2条回答 默认 最新

  • doumo1807831 2015-03-02 09:53
    关注

    i think you can do it this way..write the query as "SELECT MAX(CAST(SUBSTRING($id,4,12) AS UNSIGNED)) FROM $tbl WHERE $id LIKE '%web%'" and then increment the id as web+(max+1).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误