Programming • Updated 8 November 2026

PHP and MySQL for Beginners: Setup, Forms, PDO Database Access, Sessions and Security Basics

Learn PHP with MySQL: install XAMPP, PHP syntax, forms, connecting with PDO, CRUD operations, prepared statements, sessions and login basics, password hashing and security mistakes to avoid on shared hosting.

PHPMySQLPDOCRUDweb development
⏱ 5 min read

PHP powers a large share of websites, including WordPress, and runs on almost every shared hosting plan in India, including cPanel. Paired with MySQL, it is a practical way to build dynamic sites such as contact forms, directories and small business apps. This guide shows you how, with modern and safe practices.

Set up a local environment

  1. Install XAMPP, WAMP or Laragon, which bundle Apache, PHP and MySQL/MariaDB.
  2. Start Apache and MySQL from the control panel.
  3. Place your project in the htdocs folder, then visit http://localhost/yourproject.
  4. Use phpMyAdmin at localhost/phpmyadmin to manage databases.

PHP basics

<?php
$name = "Asha";
$items = ["pen", "book", "bag"];

echo "Hello, " . htmlspecialchars($name) . "<br>";

foreach ($items as $i => $item) {
    echo ($i + 1) . ". " . $item . "<br>";
}

function gst(float $amount, float $rate = 18): float {
    return round($amount * $rate / 100, 2);
}
echo gst(1000);
?>

PHP code lives inside <?php ... ?> tags. Variables begin with $, strings are joined with a dot, and htmlspecialchars() escapes output to prevent XSS. You can compare the result with our GST calculator.

Create a database

CREATE DATABASE notes_app CHARACTER SET utf8mb4;
USE notes_app;
CREATE TABLE notes (
  id INT AUTO_INCREMENT PRIMARY KEY,
  title VARCHAR(150) NOT NULL,
  body TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

New to queries? Read our SQL basics guide.

Connect with PDO

<?php
// db.php
$dsn = "mysql:host=localhost;dbname=notes_app;charset=utf8mb4";
$pdo = new PDO($dsn, "root", "", [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

Use PDO (or mysqli) with prepared statements. The old mysql_* functions have been removed. On live hosting, never use the root user. Create a database user with only the needed privileges and keep credentials outside the public web folder if possible.

Create and read (CRUD)

<?php
require "db.php";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $title = trim($_POST["title"] ?? "");
    $body  = trim($_POST["body"] ?? "");
    if ($title !== "") {
        $stmt = $pdo->prepare("INSERT INTO notes (title, body) VALUES (?, ?)");
        $stmt->execute([$title, $body]);
    }
    header("Location: index.php");
    exit;
}

$notes = $pdo->query("SELECT * FROM notes ORDER BY id DESC")->fetchAll();
?>
<form method="post">
  <input name="title" required>
  <textarea name="body"></textarea>
  <button>Save</button>
</form>
<?php foreach ($notes as $n): ?>
  <h3><?= htmlspecialchars($n["title"]) ?></h3>
  <p><?= nl2br(htmlspecialchars($n["body"])) ?></p>
<?php endforeach; ?>

Update and delete work the same way using UPDATE ... WHERE id = ? and DELETE ... WHERE id = ?, ideally triggered by POST requests with a CSRF token.

Sessions and login

<?php
session_start();

// registration
$hash = password_hash($_POST["password"], PASSWORD_DEFAULT);

// login
if (password_verify($_POST["password"], $user["password_hash"])) {
    session_regenerate_id(true);
    $_SESSION["user_id"] = $user["id"];
}

Never store plain-text passwords. password_hash and password_verify handle salting and strong algorithms. Regenerate the session ID on login, and set cookie flags (HttpOnly, Secure, SameSite).

Security checklist

  • Prepared statements for every query with user input.
  • Escape all output with htmlspecialchars.
  • CSRF tokens on forms that change data.
  • Validate file uploads by type and size, and store them outside the web root or with random names.
  • Hide error messages in production: display_errors = Off, log errors instead.
  • Keep PHP and libraries updated.

Moving to live hosting

  1. Create a database and user in cPanel's MySQL Databases.
  2. Export your local database from phpMyAdmin and import it on the host.
  3. Upload files via File Manager or FTP, and update the credentials.
  4. Check the PHP version selector in cPanel.

Decide whether to build custom or use a CMS by reading WordPress vs custom site. For modern JavaScript back ends, see Node.js.

Organising your PHP code

As projects grow, avoid mixing SQL, logic and HTML in one file. Put database connection code in one include, move queries into functions or small classes, and keep templates focused on display. Use consistent naming, follow the PSR coding standards, and learn Composer to manage packages. Frameworks such as Laravel make this structure automatic and are in strong demand in India, but understanding plain PHP first helps you debug them. Log errors to a file, back up your database regularly with phpMyAdmin or a cron job, and test forms with empty, very long and unexpected input. These habits keep a small site from turning into a maintenance headache.

Mini project ideas

  • Contact form with database storage: validate input, save messages, and email yourself a notification. Protect it with a honeypot field or CAPTCHA to reduce spam.
  • Simple blog: create posts, categories and an admin login with password hashing and sessions.
  • Student marks tracker: add students and subjects, calculate percentages, and print a report. You can verify results with our marks percentage calculator.
  • Product catalogue: upload images, search by name, and paginate results with LIMIT and OFFSET.

Build each project in stages: first a working version with plain forms, then validation, then security hardening, then layout. Commit each stage to Git and write down what you learned. Employers and clients value a small portfolio of working, secure projects more than a long list of technologies on a resume.

Frequently asked questions

Is PHP still relevant?

Yes, it powers a large portion of the web, including WordPress.

What is PDO?

A PHP database access layer that supports prepared statements.

How do I prevent SQL injection in PHP?

Use prepared statements with bound parameters.

How should I store passwords?

Use password_hash and password_verify, never plain text.

What is XAMPP?

A bundle of Apache, PHP and MySQL for local development.

Can I run PHP on cPanel?

Yes, most cPanel hosts support PHP and MySQL.

Last reviewed 8 November 2026. Rates, limits and rules change, so confirm figures with the official source before you act.

Keep reading

Information on AMTools is for general guidance and is not professional financial, tax, legal or medical advice. Rules, rates and limits change, so check the latest official source before acting.