create_table.php
<?php
//Config
$server = "localhost";
$user = "root";
$password = "";
$database = "address_book";
//Establishing a Connection to MySQL Server
$connection = mysqli_connect($server, $user, $password, $database);
//Check Connection
if (!$connection) {
die("<h2>Total Fail</h2> " . mysqli_connect_error());
} else {
echo "Connection Successfull <br>";
}
//SQL Command
$sql_command = "CREATE TABLE people(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
telephon INT,
email VARCHAR(100),
address VARCHAR(100),
meta TIMESTAMP
)";
//Check SQL Command
if (mysqli_query($connection, $sql_command)) {
echo "SQL Command OK";
} else {
echo "SQL ERROR" . mysqli_error($connection);
}
?>
This PHP code creates a new table named "people" in the currently selected MySQL database using the "CREATE TABLE" SQL command. The "people" table has 7 columns: "id", "name", "lastname", "telephon", "email", "address", and "meta".
The "id" column is of type INT, NOT NULL, and serves as the primary key of the table. The "name" and "lastname" columns are of type VARCHAR(30) and are also NOT NULL. The "telephon" column is of type INT and can contain phone numbers. The "email" column is of type VARCHAR(100) and can contain email addresses. The "address" column is of type VARCHAR(100) and can contain physical addresses. The "meta" column is of type TIMESTAMP and will automatically update every time a row is added or modified.
The code first stores the SQL command in the variable $sql_command. It then uses the mysqli_query function to execute the command on the MySQL database. If the query is successful, the code outputs "SQL Command OK". If there is an error, the code outputs "SQL ERROR" followed by a message describing the error returned by mysqli_error($connection).
After First Run:
Connection Successfull
SQL Command OK
After Second Run:
Connection Successfull
SQL ERROR Table 'people' already exists
No comments:
Post a Comment