One part 1 we learned how to connect a database connection with mysql.
Now on this part we will learn how to create tables, insert values into the database.
Creating table
See this Example care fully.
//connection arleady established...on part 1.
mysql_query("CREATE TABLE example(id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),name VARCHAR(30), age INT)"( or die(mysql_error());
Explanation
mysql_query();
This function is called for every query we o on database with php.
CREATE TABLE
This sql command craetes the tables in database
Syntax:
CREATE TABLE "table_name"
("column 1" "data_type_for_column_1" "Constraint_for_column_1_optional" ,
"column 2" "data_type_for_column_2" "Constraint_for_column_1_optional",
...,PRIMARY KEY(column name) )
Here the first column is id , The INT determines that the data type is Integer .
NOT NULL is a Constraint which states that the values in this column cannot be nulled.
AUTO_INCREMENT is used so that each time a new entry is added the value will be incremented by 1.
PRIMARY KEY(id)
PRIMARY KEY is used as a unique identifier for the rows. Here we have made "id" the PRIMARY KEY for this table. This means that no two ids can be the same, or else we will run into trouble. This is why we made "id" an auto incrementing counter in the previous line of code.
the other field name is a VARCHAR which stands for variable character. "character" because it stores characters (letters, numbers, etc) and "variable" because you can store a varied amount of characters in the field (from 0 up to 30).
Hope you had understood how to create a table.Now we will insert values to it.
// Insert a row of information into the table "example" created above
mysql_query("INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
mysql_query("INSERT INTO example
(name, age) VALUES('Sandy Smith', '21' ) ")
or die(mysql_error());
mysql_query("INSERT INTO example
(name, age) VALUES('Bobby Wallace', '' ) ")
or die(mysql_error());
here we added 3 entries in the example table
stntax:
INSERT INTO tablename(columnname1, columnname2) VALUES('columnname1_value', 'columnname2_value' )
Note: the location and number of apostrophes and parentheses.If it don't match with field set and values mysql error will occur.
If you want to leave a blank value you must provide a blank quote as i did on third value, where i had leaved the age value blank. But be sure the field is not set to NOT NULL.
if you had any problem please leave a comment.
now after we had inserted values we will display the values through php. Which i will discuss on my nest part.
Copyright Ayon Baidya
No comments:
Post a Comment