//Create database $con = mysql_connect("localhost","peter","abc123"); -
if ( !$con) { die('Could not connect: ' . mysql_error()); } if (mysql_query("CREATE D ATABASE my_db", $con)) { bbs.it-home.org echo "Database created"; } else { e cho "Error creating database : " . mysql_error(); } mysql_close($con); ?>
-
2, create table
CREATE TABLE is used to create a database table in MySQL.
Grammar
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
.......
)
In order to execute this command, I have to add a CREATE TABLE statement to the mysql_query() function.
Example, create a table named "Persons" with three columns. The column names are "FirstName", "LastName" and "Age":
-
- $ con = mysql_connect("localhost ","peter","abc123");
- if (!$con)
- {
- die('Could not connect: ' . mysql_error());
- }
D // Create database if (mysql_query ("Create DataBase My_db", $ Con) {bbs.it-home.org - echo "database created";
- }
- else
- {
- echo "Error creating database: " . mysql_error();
- }
- // Create table in my_db database
- mysql_select_db ("my_db", $con);
- $sql = "CREATE TABLE Persons
- (
- FirstName varchar(15),
- LastName varchar(15),
Age int- )";
- mysql_query($sql,$con);
- mysql_close($con);
- ?>
- Copy code
Important: Before creating a table, you must first select the database. Select the database through the mysql_select_db() function. -
Note: When you create a database field of varchar type, you must specify the maximum length of the field, for example: varchar(15).
MySQL data types
Various MySQL data types:
-
$sql = "CREATE TABLE Persons
(
-
personID int NOT NULL AUTO_INCREMENT,
-
PRIMARY KEY(personID) ,
-
FirstName varchar(15),
-
LastName varchar(15),
-
Age int
-
)";
mysql_query($ sql,$con);
|