MySQL Create Table

Creating a table in MySQL using PHP involves writing a script to establish a database connection and executing a SQL CREATE TABLE query.


A database table has its own unique name and consists of columns and rows.


Create a Table Using MySQLi and PDO


We will create a table named "users", with five columns: "id", "name", "email" and "created_at":




Example (MySQLi Procedural)

<!DOCTYPE html>

<html>

<head>

<title>Page Title</title>

</head>

<body>


<h1>This is a Heading</h1>

<p>This is a paragraph.</p>


</body>

</html>

Above created table explanation:


Data types are used to specify the type of data that can be stored in a table's column.


You can specify other optional attributes for each column, followed by data type.


  • UNSIGNED: Ensures the value is positive.
  • AUTO_INCREMENT: Automatically increments for each new row.
  • PRIMARY KEY: Makes id the unique identifier for each record.
  • NOT NULL: Ensures the field cannot be empty.
  • UNIQUE: Ensures no duplicate email addresses.
  • DEFAULT CURRENT_TIMESTAMP: Automatically sets the current timestamp when a record is created.
Example (Object-Oriented)
connect_error) { die("Connection failed: " . $conn->connect_error); } // Step 4: SQL query to create a table $sql = "CREATE TABLE users ( id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, -- Unique ID for each user name VARCHAR(100) NOT NULL, -- User's name email VARCHAR(100) UNIQUE NOT NULL, -- User's email (must be unique) created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- Record creation timestamp )"; // Step 5: Execute the query if ($conn->query($sql) === TRUE) { echo "Table 'users' created successfully!"; } else { echo "Error creating table: " . $conn->error; } // Step 6: Close the connection $conn->close(); ?>
Example (Procedural Method)

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.