Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

3. Creating Database & Tables

Lesson 29 of 36 in the free Web Based Programming notes on Siksha Sarovar, written by Rohit Jangra.

Creating Databases and Tables in MySQL via PHP

1. SQL Data Types — Choosing the Right Type

When designing a table, choosing the correct data type for each column is critical. It affects storage size, performance, and data integrity.

Numeric Types:

TypeRange / PrecisionUse Case
TINYINT-128 to 127 (1 byte)Age, boolean (0/1)
INT-2.1B to 2.1B (4 bytes)IDs, general integers
BIGINTVery large integers (8 bytes)Transaction IDs, huge counts
FLOAT~7 decimal digitsApproximate decimal values
DECIMAL(p,s)Exact decimal, up to p digits with s decimal placesMoney, prices (use DECIMAL, not FLOAT, for money!)

String Types:

TypeDescriptionUse Case
CHAR(n)Fixed-length string, always n chars (padded with spaces)Phone numbers, codes
VARCHAR(n)Variable-length string, up to n charsNames, emails, usernames
TEXTLong variable-length stringComments, blog content
ENUM('v1','v2')Only allows specified valuesStatus ('Active','Inactive')

Date and Time Types:

TypeFormatUse Case
DATEYYYY-MM-DDBirthdates, event dates
DATETIMEYYYY-MM-DD HH:MM:SSCreated/updated timestamps
TIMESTAMPLike DATETIME, auto-updates on changesLast modified tracking
TIMEHH:MM:SSDuration

2. Table Constraints

Definition: Constraints are rules enforced on columns to ensure data integrity — preventing invalid or inconsistent data from being stored.

ConstraintDefinitionExample
NOT NULLColumn cannot be empty/NULLname VARCHAR(50) NOT NULL
PRIMARY KEYUniquely identifies each row; cannot be NULL or duplicateid INT PRIMARY KEY
AUTO_INCREMENTAutomatically generates the next sequential integerid INT AUTO_INCREMENT
UNIQUEAll values in the column must be distinctemail VARCHAR(100) UNIQUE
DEFAULTProvides a default value if none is specifiedstatus VARCHAR(10) DEFAULT 'Active'
FOREIGN KEYLinks to the primary key of another tableFOREIGN KEY (dept_id) REFERENCES departments(id)

3. Creating a Database

<?php
$conn = new mysqli("localhost", "root", "");
if ($conn->connect_error) die("Connection Failed");

$sql = "CREATE DATABASE CollegeDB";
if ($conn->query($sql) === TRUE) {
  echo "Database 'CollegeDB' created successfully!";
} else {
  echo "Error creating database: " . $conn->error;
}
$conn->close();
?>

4. Creating a Table (Complete Example)

<?php
$conn = new mysqli("localhost", "root", "", "CollegeDB");

$sql = "CREATE TABLE students (
  id         INT         UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name       VARCHAR(50) NOT NULL,
  email      VARCHAR(100) UNIQUE NOT NULL,
  course     VARCHAR(30) NOT NULL,
  marks      DECIMAL(5,2) DEFAULT 0.00,
  enrolled   DATE         NOT NULL,
  is_active  TINYINT(1)   DEFAULT 1,
  created_at TIMESTAMP    DEFAULT CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {
  echo "Table 'students' created successfully!";
} else {
  echo "Error: " . $conn->error;
}
$conn->close();
?>

5. Modifying a Table with ALTER TABLE

After creation, you can modify a table's structure without losing data.

// Add a new column
$sql = "ALTER TABLE students ADD COLUMN phone VARCHAR(15)";
$conn->query($sql);

// Change a column's data type
$sql = "ALTER TABLE students MODIFY COLUMN marks DECIMAL(6,2)";
$conn->query($sql);

// Rename a column (MySQL 8.0+)
$sql = "ALTER TABLE students RENAME COLUMN phone TO mobile";
$conn->query($sql);

// Remove a column
$sql = "ALTER TABLE students DROP COLUMN mobile";
$conn->query($sql);

6. Checking if a Table Exists Before Creating

$sql = "CREATE TABLE IF NOT EXISTS products (
  id   INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  price DECIMAL(8,2)
)";
$conn->query($sql); // Safe — won't error if already exists