To create a table in a MySQL database using PHP, you can execute an SQL CREATE TABLE query. Below are examples using both mysqli and PDO to create a table in a MySQL database.
Here's an example using mysqli to create a table named users with three columns: id, name, and email.
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to create a table
$sql = "CREATE TABLE IF NOT EXISTS users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
)";
// Execute the query
if ($conn->query($sql) === TRUE) {
echo "Table 'users' created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Close connection
$conn->close();
Here's the same example using PDO :
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
try {
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// SQL query to create a table
$sql = "CREATE TABLE IF NOT EXISTS users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
)";
// Prepare and execute the query
$stmt = $conn->prepare($sql);
$stmt->execute();
echo "Table 'users' created successfully";
} catch (PDOException $e) {
echo "Error creating table: " . $e->getMessage();
} finally {
// Close connection
$conn = null;
}
Running this script will create the users table in your specified database. If the table already exists, it will not be recreated, ensuring that existing data is preserved.