How to insert the next highest number into the database

前端 未结 3 1393
伪装坚强ぢ
伪装坚强ぢ 2021-01-26 17:15

I have a piece of mysqli code which I written where it will insert values into the database:

$insertsql = \"
INSERT INTO Teacher
    (TeacherId, TeacherForename,         


        
相关标签:
3条回答
  • 2021-01-26 17:19

    Change TeacherId from a varchar to an int. The create table will look a bit like this:

    CREATE TABLE Teacher (
       TeacherId int unsigned not null auto_increment primary key
    

    The auto_increment will start from 1 and automatically increase by 1 on each insert.

    If you must prepend the T, you can always do it with CONCAT or in the php code.

    0 讨论(0)
  • 2021-01-26 17:29

    Well you can try this:

    First get the total number of rows in the table and increment it by 1 and put that into your new id For example:

    $selectUsers = mysql_query ("SELECT * FROM `Teacher`") or die(mysql_error());
    $num_rows = mysql_num_rows($selectUsers);
    
    $next_id = $num_rows+1;
    
    $new_id = 'T'.$next_id ;
    

    and after insert it into the table:

    ...

    0 讨论(0)
  • 2021-01-26 17:38

    You could do something like this. It is an auto incrementing primary key column with a formatted column. I have not had a chance to test this.

    CREATE TABLE Teacher (
      TeacherId mediumint UNSIGNED AUTO_INCREMENT PRIMARY_KEY,
      TeacherIdF varchar(6) AS 'T_' + CONVERT(varchar, TeacherId),
      ...
      CONSTRAINT Teacher_UKey01 UNIQUE (TeacherIdF)
    )
    

    If the constraint does not work, you can create a trigger that will update the column after a row is inserted.

    CREATE TABLE Teacher (
      TeacherId mediumint UNSIGNED AUTO_INCREMENT PRIMARY_KEY,
      TeacherIdF varchar(6) NULL
      ...
    )
    
    CREATE TRIGGER FormattedTeacherId
    AFTER insert ON Teacher
    BEGIN
    UPDATE Teacher SET TeacherIdF = CONCAT('T', TeacherId)
    END
    

    I have not tested this code.

    0 讨论(0)
提交回复
热议问题