Learn PHP Programming

Master PHP programming from basics to advanced concepts with our comprehensive tutorial series. Perfect for beginners and web developers.

PHP Database & MySQL

Learn how to connect PHP to MySQL using PDO, perform CRUD operations with prepared statements, and manage transactions safely.

1. PDO Connection with Error Handling

PDO (PHP Data Objects) provides a consistent interface for database access. Always configure proper options for security and debugging.

connection.php
<?php
// Database configuration
$host = 'localhost';
$dbname = 'my_application';
$username = 'db_user';
$password = 'db_password';
$charset = 'utf8mb4';

// DSN (Data Source Name)
$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";

// PDO options for security and performance
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,    // Throw exceptions on errors
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,          // Return associative arrays
    PDO::ATTR_EMULATE_PREPARES   => false,                     // Use real prepared statements
    PDO::ATTR_STRINGIFY_FETCHES  => false,                     // Keep native data types
];

try {
    $pdo = new PDO($dsn, $username, $password, $options);
    echo "Connected successfully!";
} catch (PDOException $e) {
    // Log the error, don't expose details to users
    error_log("Database connection failed: " . $e->getMessage());
    die("A database error occurred. Please try again later.");
}
?>

2. INSERT with Prepared Statements

Use prepared statements with either named or positional placeholders to safely insert data.

insert.php
<?php
// Named placeholders (recommended for readability)
$sql = "INSERT INTO users (name, email, age) VALUES (:name, :email, :age)";
$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':name'  => 'Alice Johnson',
    ':email' => 'alice@example.com',
    ':age'   => 28
]);
$lastId = $pdo->lastInsertId();
echo "Inserted user with ID: $lastId";

// Positional placeholders (shorter syntax)
$sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute(['Bob Smith', 'bob@example.com', 35]);

// Insert multiple rows efficiently
$users = [
    ['Charlie', 'charlie@example.com', 22],
    ['Diana', 'diana@example.com', 30],
];
$sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)";
$stmt = $pdo->prepare($sql);
foreach ($users as $user) {
    $stmt->execute($user);
}
?>

3. SELECT with Fetch Modes

PDO supports multiple fetch modes to retrieve data in the format that suits your needs.

select.php
<?php
// FETCH_ASSOC - Returns associative array
$stmt = $pdo->prepare("SELECT * FROM users WHERE age > ?");
$stmt->execute([25]);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($users as $user) {
    echo $user['name'] . " - " . $user['email'] . "\n";
}

// FETCH_OBJ - Returns anonymous objects
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute([':email' => 'alice@example.com']);
$user = $stmt->fetch(PDO::FETCH_OBJ);
echo $user->name;  // Access properties with arrow notation

// FETCH_CLASS - Maps results to a class
class User {
    public $id;
    public $name;
    public $email;

    public function getDisplayName() {
        return strtoupper($this->name);
    }
}
$stmt = $pdo->prepare("SELECT id, name, email FROM users");
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_CLASS, 'User');
foreach ($users as $user) {
    echo $user->getDisplayName() . "\n";
}
?>

4. UPDATE and DELETE

Always use parameterized queries for UPDATE and DELETE operations to prevent injection and ensure correct row targeting.

update_delete.php
<?php
// UPDATE with named placeholders
$sql = "UPDATE users SET email = :email, age = :age WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':email' => 'newalice@example.com',
    ':age'   => 29,
    ':id'    => 1
]);
echo "Updated " . $stmt->rowCount() . " row(s)";

// DELETE with confirmation check
$sql = "DELETE FROM users WHERE id = ? AND email = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([42, 'old@example.com']);
if ($stmt->rowCount() === 0) {
    echo "No matching record found to delete.";
} else {
    echo "Deleted successfully.";
}
?>

5. Transactions

Transactions ensure that a group of queries either all succeed or all fail together, maintaining data integrity.

transactions.php
<?php
// Transfer money between accounts (must be atomic)
try {
    $pdo->beginTransaction();

    // Debit from sender
    $stmt = $pdo->prepare("UPDATE accounts SET balance = balance - :amount WHERE id = :id AND balance >= :amount");
    $stmt->execute([':amount' => 100.00, ':id' => 1]);
    if ($stmt->rowCount() === 0) {
        throw new Exception("Insufficient funds or account not found.");
    }

    // Credit to receiver
    $stmt = $pdo->prepare("UPDATE accounts SET balance = balance + :amount WHERE id = :id");
    $stmt->execute([':amount' => 100.00, ':id' => 2]);
    if ($stmt->rowCount() === 0) {
        throw new Exception("Receiver account not found.");
    }

    // Log the transaction
    $stmt = $pdo->prepare("INSERT INTO transfers (from_id, to_id, amount, created_at) VALUES (?, ?, ?, NOW())");
    $stmt->execute([1, 2, 100.00]);

    $pdo->commit();
    echo "Transfer completed successfully!";
} catch (Exception $e) {
    $pdo->rollBack();
    echo "Transfer failed: " . $e->getMessage();
    error_log("Transaction error: " . $e->getMessage());
}
?>

Key Takeaways

  • Always use PDO with ERRMODE_EXCEPTION and EMULATE_PREPARES => false for secure, real prepared statements.
  • Never concatenate user input into SQL queries — use named (:param) or positional (?) placeholders.
  • Choose the right fetch mode: FETCH_ASSOC for arrays, FETCH_OBJ for quick objects, FETCH_CLASS for typed models.
  • Use transactions for any operation that involves multiple related queries to maintain data consistency.
  • Handle errors gracefully: log detailed errors server-side and show generic messages to users.
Best Practice Alert

Store database credentials in environment variables or a configuration file outside the web root. Never hardcode passwords in source files or commit .env files to version control. Use connection pooling in production for better performance.

Keywords: PDO, prepared statements, parameter binding, fetch modes, transactions, CRUD, MySQL, database security

Frequently Asked Questions

PHP is a server-side scripting language designed for web development. It powers over 75% of websites on the internet, including Facebook, Wikipedia, and WordPress. Learning PHP opens doors to web development careers and freelance opportunities.

No, PHP is beginner-friendly with simple syntax. However, basic understanding of HTML and CSS will be helpful since PHP is often used to create dynamic web pages.

With PHP, you can build dynamic websites, web applications, content management systems, e-commerce platforms, APIs, and much more. Popular platforms like WordPress, Drupal, and Magento are built with PHP.

Basic PHP can be learned in 2-4 weeks with consistent practice. To become proficient and learn advanced concepts like frameworks and best practices, it typically takes 3-6 months of regular learning and practice.

You need a web server (Apache/Nginx), PHP interpreter, and a database (MySQL). The easiest way is to install XAMPP, WAMP, or MAMP which includes all these tools. You'll also need a text editor like VS Code or PhpStorm.

PHP Programming Tutorial — Learn PHP from Scratch

PHP (PHP: Hypertext Preprocessor) is the most widely-used server-side scripting language for web development. It powers over 77% of all websites with known server-side languages, including WordPress, Facebook, Wikipedia, and Slack. This comprehensive tutorial series takes you from complete beginner to confident PHP developer with hands-on examples you can run and modify.

Each topic in this tutorial includes multiple runnable code examples with line-by-line explanations, best practice tips, and navigation to the next logical concept. Whether you are learning PHP for the first time or refreshing your knowledge of a specific feature, every page is designed to give you practical, immediately-usable code.

What You Will Learn in This PHP Tutorial

  • Basics: Syntax, variables, constants, data types, operators
  • Strings & Arrays: Manipulation, searching, sorting, multidimensional arrays
  • Control Flow: if/else, switch, for, while, foreach loops
  • Functions: Parameters, return values, scope, anonymous functions
  • Superglobals: $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER
  • Forms: Handling user input, validation, file uploads
  • File Handling: Reading, writing, and manipulating files
  • Sessions & Cookies: User state management across requests
  • OOP: Classes, objects, inheritance, interfaces, traits
  • Error Handling: try/catch, custom exceptions, error reporting
  • Database: MySQL connection, CRUD operations, prepared statements
  • Security: SQL injection prevention, XSS, CSRF, password hashing

Why Learn PHP in 2026?

Despite the rise of Node.js and Python, PHP remains the backbone of web development for compelling reasons:

  • Job market demand: Thousands of PHP developer positions available globally. WordPress alone powers 43% of all websites and requires PHP.
  • Framework ecosystem: Laravel (the most popular web framework), Symfony, CodeIgniter, and Slim provide professional-grade tooling.
  • Low barrier to entry: Shared hosting supports PHP out of the box. No complex server configuration needed to get started.
  • PHP 8.x improvements: JIT compiler, named arguments, match expressions, union types, fibers — modern PHP is fast and expressive.
  • CMS dominance: WordPress, Drupal, Joomla, Magento, WooCommerce all run on PHP. Knowing PHP gives you access to this entire ecosystem.
  • Freelancing opportunities: PHP projects dominate freelance platforms. Many small businesses need WordPress customisation and PHP-based solutions.

PHP Version History (Key Milestones)

VersionYearKey Features
PHP 5.02004Full OOP support, PDO, improved XML
PHP 7.020152x speed improvement, scalar type declarations, null coalesce operator
PHP 7.42019Arrow functions, typed properties, preloading
PHP 8.02020JIT compiler, named arguments, match expression, union types, attributes
PHP 8.12021Enums, fibers, readonly properties, intersection types
PHP 8.22022Readonly classes, DNF types, deprecate dynamic properties
PHP 8.32023Typed class constants, json_validate(), #[Override] attribute

How to Get Started with PHP

  1. Install a local environment — download XAMPP (Windows/Mac/Linux) or Laravel Valet (Mac). This gives you Apache, PHP, and MySQL in one package.
  2. Create your first file — make a file called index.php in your web root and add: <?php echo "Hello, World!"; ?>
  3. Run it in browser — start Apache and visit http://localhost/index.php to see output.
  4. Follow this tutorial series — work through each topic in order, running every example on your local setup.
  5. Build a project — after completing basics through OOP, build a simple CRUD app (todo list, blog, or contact form) to solidify your knowledge.

Frequently Asked Questions

Do I need to know HTML before learning PHP?

Basic HTML knowledge is helpful since PHP is often embedded in HTML pages. You do not need to be an HTML expert — understanding tags, forms, and page structure is enough to start.

Is PHP still relevant with frameworks like React/Next.js?

Yes. PHP and React serve different roles. React is frontend; PHP is backend. Laravel (PHP) is often used as the API backend for React frontends. WordPress (PHP) powers 43% of the web. The job market for PHP developers remains strong.

Which PHP framework should I learn first?

Laravel is the most popular and has the best documentation, ecosystem, and community. Learn core PHP first (this tutorial), then move to Laravel. Other options: Symfony (enterprise), CodeIgniter (lightweight), Slim (microframework for APIs).

Can I run PHP code online without installing anything?

Yes. Use our free online code editors to write and execute PHP code directly in your browser. This is perfect for learning and testing snippets without local setup.

Who Is This Tutorial For?

Complete beginners who want to learn their first programming language for web development. Self-taught developers filling gaps in their PHP knowledge. Students preparing for web development courses or exams. WordPress developers who want to understand the PHP underneath themes and plugins. Backend developers from other languages (Python, Node.js) learning PHP for a new project. Anyone preparing for PHP developer job interviews.

Master PHP Programming with Our Comprehensive Tutorial

Our PHP programming tutorial is designed to take you from a complete beginner to an advanced PHP developer. Whether you're looking to build dynamic websites, create web applications, or start a career in web development, this tutorial series provides everything you need to succeed.

What You'll Learn

  • PHP fundamentals and syntax
  • Variables, data types, and operators
  • Control structures and loops
  • Functions and arrays
  • Object-oriented programming
  • Database integration with MySQL
  • Web forms and user input handling
  • Security best practices

PHP remains one of the most popular programming languages for web development, powering millions of websites worldwide. Our tutorial includes practical examples, real-world projects, and best practices to ensure you learn not just the syntax, but how to write clean, efficient, and secure PHP code.