Search code examples
phpsqlphpmyadminauto-increment

How to make a primary key to auto increment in a database in php?


I have a database and i am putting data inside. I have one node called key , which is the primary key and other nodes. Now when i put data on my table , i put data in all the nodes except this key node. How do i make it automatically to increase from 0 when i have a new entry? If i run a script to put something in the database , i can see that the nodes have correctly all the data and the key takes the value 0. When i run my script again i get the error :

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY'' 

From what i understand , because i dont pass anything to this node , the database "thinks" i am passing again a 0 argument so i have the error. How can i fix it to auto increment every time i have a new entry?


Solution

  • You need to set the field as autoincrement. You would need to run an ALTER TABLE statement like this:

    ALTER TABLE table_name
    MODIFY `key` MEDIUMINT NOT NULL AUTO_INCREMENT