php – How can I increment a column when inserting values into a database table without using AUTO INCREMENT-ThrowExceptions

Exception or error:

I’ve got a column inside my database “#”, I would like to increment that for each insert statement I do.

$sql = "INSERT INTO card (#,creditCard, expdate, cvv)
            VALUES ('','$creditCardStore','2020-01-01','$cvv')";

I can’t alter the table to use AUTO INCREMENT.

I found this on the web but i don’t know what to put inside the for(..)

$value = 1;
for(...){
 $sql = 'INSERT ...'; 
 $value++; 
}
How to solve:

Well you could try inserting the previous max value for # in your table, plus one:

INSERT INTO card (num, creditCard, expdate, cvv)
SELECT MAX(num) + 1, ?, '2020-01-01', ?
FROM card;

Here I am using ? placeholders for the credit card store and verification code, under the assumption that you should be using a PHP prepared statement.

Answer:

How about checking what the last # was, set it as an variable and increase another varible and insert that variable?

Something like this (This is not a valid code, just a description from what I meant above)
SELECT # FROM card LIMIT 1 ORDER BY # ASC

n1 = #
n2 = # + 1

and then in value, insert n2.

Answer:

Try this it will work, simply add plus one in this column.

$sql = "INSERT INTO card set id=id+1,creditCard='$creditCardStore', expdate=''2020- 
    01-01', cvv='$cvv'";

Leave a Reply

Your email address will not be published. Required fields are marked *