PHP MySQL Create Tables
In this tutorial you will learn how to create tables in MySQL database using PHP.
Creating Tables inside MySQL Database Using PHP
In the previous chapter we've learned how to create a database on MySQL server. Now it's time to create some tables inside the database that will actually hold the data. A table organizes the information into rows and columns.
The SQL
CREATE TABLE
statement is used to create a table in database.
Let's make a SQL query using the
CREATE TABLE
statement, after that we will execute this SQL query through passing it to the PHP mysqli_query()
function to finally create our table./* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt create table query execution
$sql = "CREATE TABLE persons(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
email VARCHAR(70) NOT NULL UNIQUE
)";
if(mysqli_query($link, $sql)){
echo "Table created successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
The PHP code in the above example creates a table named persons with four columns id, first_name, last_name and email inside the demo database.
Notice that each field name is followed by a data type declaration; this declaration specifies what type of data the column can hold, whether integer, string, date, etc.
There are a few additional constraints (also called modifiers) that are specified after the column name in the preceding SQL statement, like
NOT NULL
, PRIMARY KEY
, AUTO_INCREMENT
, etc. Constraints define rules regarding the values allowed in columns.
Please check out the tutorial on SQL
CREATE TABLE
statement for the detailed information about syntax, as well as the data types and constraints available in MySQL database system.
Note: Any number of line breaks may occur within a SQL statement, provided that any line break does not break off keywords, values, expression, etc.
Tip: Setting the
PDO::ATTR_ERRMODE
attribute to PDO::ERRMODE_EXCEPTION
tells PDO to throw exceptions whenever a database error occurs.
0 comments:
Post a Comment