How do I create a table in a MySQL DB? Print

  • 2

The following example shows how you can create a table named "person", with three columns. The column names will be "FirstName", "LastName" and "Age":


<?php
$con = mysql_connect("localhost","YourDB_username","YourDB_password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }//
Create database
if (mysql_query("CREATE DATABASE my_db",$con))
  {
  echo "Database created";
  }
else
  {
  echo "Error creating database: " . mysql_error();
  }// Create table in my_db database
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE person
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);mysql_close($con);
?>


Important: A database must be selected before a table can be created. The database is selected with the mysql_select_db() function.

Note: When you create a database field of type varchar, you must specify the maximum length of the field, e.g. varchar(15).

*** Also it is possible to import a .sql query to phpMyAdmin


Was this answer helpful?

« Back