- The CREATE DATABASE statement is used to create a database in MySQL:
-
1
CREATE DATABASE database_name
- To get PHP to execute the statement above you should use the mysql_query() function. This function is used to send a query or command to a MySQL connection.
- This example code shows how to create a database named “my_db”:
-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } mysql_close($con); ?>
- To create a table in mysql, use The CREATE TABLE statement:
-
CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... )
- Also, the CREATE TABLE statement should be added to the mysql_query() function in order to execute the command.
- The following example creates a table named "Persons", with three columns. The column names will be "FirstName", "LastName" and "Age":
-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // Create database if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } // Create table mysql_select_db("my_db", $con); $sql = "CREATE TABLE Persons ( FirstName varchar(15), LastName varchar(15), Age int )"; // Execute query mysql_query($sql,$con); mysql_close($con); ?>
- MySQL Introduction
- MySQL Connect
- MySQL Insert
- MySQL Select


