Saving a value from database


#1

Hey! So I am trying to retrieve the highest ID value from my database, add 1, then insert that new value into a new row. I have the rest of my code working apart from this part, am I going about storing this wrong?

  $id = mysql_query($con, "SELECT ticketID FROM tickets ORDER BY ticketID DESC LIMIT 0, 1");
  $bookid = ($id + 1);
   
    $query = mysqli_query($con, "INSERT INTO tickets (ticketID) VALUES 
   ('$bookid')");

#2

This is not how to do this. When there are multiple concurrent instances of your code all doing this, they will all get the same starting value, increment it and insert the same value, so you will randomly end up with duplicate values, which should produce a query error (the ticketID column should be defined as a unique index.)

The correct way to do this is to define the ticketID column as an auto-increment primary index, then just insert a new row and get the last insert id from that row.


#3

Ah, i see what you mean about auto-increment primary index, got that sorted! thanks!

Though for future, If I want to take a value from the database and save that value for use, can you show me an example of how to do that the correct way?


#4

My first thought would be, why would you want/ need to do that? More than likely, you are thinking about it a different way than you should.


#5

Is it possible though? I didn’t think it would be too tricky


#6

Either you have a typo or you are mixing mysql and mysqli.


#7

It’s possible. It’s more than likely incorrect.


#8

I got it too work! thanks though