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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。