What needs to be put in the SQL statement for an automatically generated field?

The first column of my MySQL table is the auto-incremented primary key. I am trying to add a new line with PHP like this.

mysql_query("INSERT INTO users VALUES ('', '$username', '$hashedPassword')"); 

What should I put in '' or in the first field? It is generated automatically, but I do not want the field to be empty.

Interestingly, creating a field empty works, but I'm afraid if this happens in certain circumstances, I did not encounter it. What is a standard entity?

Also, does your solution also apply to timestamp fields that default to current time?

I am new to PHP and MySQL. Thanks.

+4
source share
6 answers

It’s good to get used to indicate your fields like this

 INSERT INTO users (username,password) VALUES ( '$username', '$hashedPassword') 

Or, if you want to specify the id field, also use NULL

 INSERT INTO users (id,username,password) VALUES (NULL, '$username', '$hashedPassword') 

By specifying the fields, your code is less likely to break if, for example, you add an additional field to the table.

+1
source

INSERT INTO users ('username', 'hashedpassword') VALUES ('$username', '$hashedPassword')

You do not need to reference the automatically generated id field, as it will be processed by MySQL.

+2
source

You can use NULL .

But it’s better to specify the columns explicitly and simply omit this column.

 INSERT INTO users (username, hashedPassword) VALUES ('$username', '$hashedPassword') 

From the MySQL manual:

The AUTO_INCREMENT column does not contain a value, so MySQL automatically assigned sequence numbers. You can also explicitly assign NULL or 0 to a column to generate sequence numbers.

+1
source

If it automatically increases the column, then do not specify anything. You must also explicitly specify all the columns that you are going to insert. Try the following:

 INSERT INTO users (username, password) VALUES ('$username', '$hashedPassword'); 
+1
source

The purpose of auto_increment is to do nothing. You MUST save it NULL or DEFAULT, or not include it as the value you are inserting / updating. It is built into MySQL MySQL

+1
source

As others have indicated, indicate which columns you want to add data to. Once you do this, you can omit the primary key column, and the DBMS will take care of this for you.

+1
source

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


All Articles