How to Set the Default Value of a Column of a MySQL Table Using PHP 


               


How to Set the Default Value of a Column of a MySQL Table Using PHP



PHP







In this article, we show how to set the default value of a column of a MySQL table using PHP.

So with SQL query languages, like MySQL, a user has the option have setting the default value of a column.

The default value is the value that the column will contain by default. This means that without the user specifying a value for the row the user inserts, the value for that particular column will contain this default value.

Most of the time, this is not used, because you want the user to enter in the value for a column. But in certain circumstances, you may want a value specified by default.

For example, say, you are hosting an event for locals and you're in the state of NY. So you expect most people attending the event to be from NY. So, say, you want to store the user's address, for instance. You may have the user enter in his or her street address and city, but have the state and country column (if it exists) entered in by default, to save the user time typing it in. You may need the user's address to mail them information about future events and so on.

So this would be a use of specifying a default value for a column in MySQL.

The general format of the MySQL query to set the default value of a column of a MySQL table is shown below.





So the above is the MySQL code to set a default value for the state column in the customers table to a default value of NY.

So all rows in the state column will have NY as their entered in default value, unless the user overrides this by entering in a value.

Again, putting in default values in a table, especially when that's what the value will be the vast majority of the time, saves time.

We'll now show how to tie this in with PHP.



So, first, we must connect to the database.

After we do this, we create a variable named $setdefault. This $setdefault variable is set equal to a mysql_query() function that has the parameter "ALTER TABLE customers ALTER state SET DEFAULT 'NY'". This sets the default value of the state column to NY.

So this is how you can set the default value of all of the rows of a column of a MySQL table using PHP.


Related Resources

How to Drop the Default Value of a Column Of a MySQL Table Using PHP

How to Add a Column to a MySQL Table Using PHP

How to Add a Primary Key to a Column of a MySQL Table Using PHP

How to Make a Column of a MySQL Table Unique Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

HTML Comment Box is loading comments...