All Tutorials

Your One-Stop Destination for Learning and Growth

Creating an MySQL Table using PHP Script

In this blog post, we will discuss how to create an MySQL table using a PHP script. This can be useful for those who want to manage their database through PHP or need to create tables dynamically based on user input.

Prerequisites

Before we start, ensure that you have the following:

  • A basic understanding of PHP and MySQL
  • A local development environment with PHP, MySQL server installed

Creating a New Database

First, let's create a new database using the mysqli_query() function. Replace newdb with your desired database name.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "newdb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
?>

Creating a Table

Now let's create a new table named users. Replace the column names and data types according to your requirement.

<?php
// Create table query
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
password VARCHAR(30) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX (username),
INDEX (email)
)";

// Execute query
if ($conn->query($sql) === TRUE) {
  echo "Table 'users' created successfully.";
} else {
  echo "Error creating table: " . $conn->error;
}
?>

Conclusion

In this blog post, we learned how to create an MySQL table using a PHP script. We started by setting up a database connection and then proceeded to create a new table with the required columns and data types. Remember that creating tables dynamically can be risky if not handled carefully; always validate user inputs before executing any queries. Happy coding!

$conn->close();
?>

Published November, 2015