Welcome to CodeYourCraft's PHP MySQLi Create Table tutorial! In this lesson, we'll guide you through creating tables in MySQL using PHP's MySQLi extension. By the end of this tutorial, you'll have a solid understanding of how to create, manage, and manipulate tables in a MySQL database using PHP. Let's get started! π
MySQLi, an extension of the PHP programming language, allows communication between PHP and MySQL databases. It provides improved performance and a more natural programming interface compared to the older MySQL extension.
MySQLi is popular due to its enhanced performance, object-oriented programming support, and better error handling capabilities. It's an excellent choice for creating robust and scalable web applications.
Before you can interact with a MySQL database, you'll need to establish a connection. Here's a simple example of creating a connection using MySQLi:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// Create a new MySQLi object
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>π In the code above, we first declare the server's name, username, password, and database name. Then, we create a new MySQLi object and establish a connection to the database.
Now that we have a connection, let's create a table! Here's an example of creating a simple table called "users":
<?php
// Create a new table called 'users'
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
registration_date TIMESTAMP
)";
// Execute the query
if ($conn->query($sql) === TRUE) {
echo "Table 'users' created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
?>π In the code above, we create a SQL query to create a table called 'users'. The table has five columns: id, firstname, lastname, email, and registration_date. We then execute the query and display a success message if it runs correctly.
id (INT) - Unique identifier for each row in the tablefirstname (VARCHAR) - User's first namelastname (VARCHAR) - User's last nameemail (VARCHAR) - User's email addressregistration_date (TIMESTAMP) - Date and time the user registeredWhat does the `CREATE TABLE` SQL command do?
Stay tuned for our upcoming tutorials on inserting, updating, and deleting data in this table using PHP MySQLi! π―