SQL Query increment 1 from last line?

since you cannot automatically increase two columns so that Query would get the last row of the table and the value of +1 column to insert a new row.

For example, I have a table called players

looks like that:

 id player_id player_name 1 15 name1 2 16 name2 3 17 name3 

I am trying to create an admin panel to create a player from a form, and the number of id identifiers automatically increases, but I also need player_id to increase too, but id and player_id do not match.

A query like this (I did this so you can understand a little better)

 $sql="select top 1 * from `players` order by id desc"; $result =mysql_query($sql); while ($data=mysql_fetch_assoc($result)){ $playerid=$data['player_id']; Insert into `players` (`player_id`,`player_name`) VALUE ('$playerid' + '1', 'name4'); } 
+4
source share
3 answers

Try this code:

  $sql="SELECT player_id FROM `players` ORDER BY id DESC LIMIT 1"; $result =mysql_query($sql); while ($data=mysql_fetch_assoc($result)){ $playerid=$data['player_id']+1; } mysql_query("Insert into `players` (`player_id`,`player_name`) VALUES ('".$playerid."','name4')"); 
+4
source

The following request will assign the next available player_id on insertion.

 INSERT INTO `players` (`player_id`, `player_name`) SELECT MAX(`player_id`)+1, 'name4' FROM `players`; 
+2
source

Try this way

  $sql="SELECT * FROM `players` ORDER BY id DESC LIMIT 1"; $result =mysql_query($sql); $data=mysql_fetch_assoc($result); $playerid=$data['player_id']+1; mysql_query("Insert into `players` (`player_id`,`player_name`) VALUES ('".$playerid."','name4')"); 
0
source

Source: https://habr.com/ru/post/1440921/


All Articles