Comprehensive Guide to Getting Started with PHP: Installation, Core Concepts, Forms, and MySQL Integration
Summary
Comprehensive Guide to Getting Started with PHP: Installation, Core Concepts, Forms, and MySQL Integration
Introduction
- PHP is a server‑side scripting language used to generate dynamic web pages. Despite rumors of its demise, it powers roughly 70% of all websites.
- Originally called Personal Home Page, the acronym now stands for PHP: Hypertext Preprocessor.
- The mascot is an elephant named Ella.
Setting Up the Development Environment
- Install XAMPP (or similar LAMP stack)
- Download from
apachefriends.organd install the Apache, MySQL, and PHP components. - Start Apache and MySQL services via the XAMPP control panel; ensure the modules turn green.
- Install Visual Studio Code
- Download from
code.visualstudio.comand follow the standard installer steps. - Recommended extensions: PHP Intellisense, Live Server, PHP Server.
- Configure VS Code to Recognize PHP
- Edit the
settings.jsonfile to setphp.validate.executablePathto the full path ofphp.exeinside the XAMPP folder.
Your First PHP File
- Create a folder
websiteinsidexampp/htdocs. - Inside that folder, create
index.php. - Basic syntax: ```php
``
- Access it viahttp://localhost/website`.
- Use the Live Server extension for automatic reloads.
Comments and Mixing HTML
- Single‑line comment:
// comment text - Multi‑line comment:
/* comment block */ - PHP files can contain HTML, CSS, and JavaScript alongside PHP code.
Variables and Data Types
| Type | Example | Description |
|---|---|---|
| String | $name = "John"; | Text, can include spaces. |
| Integer | $age = 21; | Whole numbers, no quotes. |
| Float | $price = 4.99; | Numbers with a decimal part. |
| Boolean | $isAdult = true; | true or false. |
- Use echo to output variables. Concatenate with . or embed inside double‑quoted strings using {}. |
Basic Arithmetic Operators
+addition,-subtraction,*multiplication,/division,**exponentiation,%modulus.- Increment/Decrement:
++$i,$i++,--$i,$i--. - Compound assignment:
$i += 2;,$i -= 3;. - Operator precedence follows PEMDAS (parentheses → exponents → multiplication/division/modulus → addition/subtraction).
Handling Form Data: GET vs POST
- GET appends data to the URL; useful for non‑sensitive queries, bookmarking, and caching.
- POST sends data in the request body; preferred for passwords, sensitive information, and large payloads.
- Access data via super‑globals:
php $username = $_GET['username']; // or $_POST['username'] - Always check with
isset()before using the variable.
Common Form Exercises
- Order Form – calculate total price (
quantity * price). - Arithmetic Calculator – accept two numbers and perform addition, subtraction, etc.
- Radius Calculator – compute circumference, area, and sphere volume using
pi()andpow().
Conditional Logic
- If / Else / Elseif syntax:
php if ($age >= 18) { echo "You may enter"; } elseif ($age < 0) { echo "Invalid age"; } else { echo "You must be 18+"; } - Comparison operators:
==,===,!=,<,>,<=,>=. - Boolean variables can be used directly in conditions.
Logical Operators
- AND –
&& - OR –
|| - NOT –
! - Example:
if ($age >= 18 && $citizen) { echo "You can vote"; }
Switch Statements
- Cleaner alternative to many
elseifbranches. - Syntax:
php switch ($grade) { case 'A': echo "Excellent"; break; case 'B': echo "Good"; break; default: echo "Invalid grade"; } - Remember to include
break;to prevent fall‑through.
Loops
- For Loop – ideal when the number of iterations is known.
php for ($i = 0; $i < 5; $i++) { echo $i; } - While Loop – runs while a condition remains true; useful for indefinite or event‑driven processes.
- Do‑while (not covered but similar to while).
- Use
break;to exit early,continue;to skip an iteration.
Arrays
- Indexed arrays:
$fruits = array('Apple', 'Orange');– access via$fruits[0]. - Associative arrays:
$capitals = array('USA' => 'Washington', 'Japan' => 'Tokyo');– access via$capitals['Japan']. - Common functions:
count($array)– number of elements.array_push($array, $value)– add to end.array_pop($array)– remove last.array_shift($array)– remove first.array_reverse($array)– reverse order.array_keys($assoc)/array_values($assoc)– retrieve keys or values.foreach ($array as $key => $value) { ... }– iterate.
Input Validation Helpers
isset($var)– true if variable exists and is notnull.empty($var)– true if variable is empty,null,false, or an empty string.- Combine with
ifstatements to provide user feedback.
Working with Radio Buttons and Checkboxes
- Give all radio inputs the same
nameattribute to enforce a single selection. - Checkboxes with the same name can be treated as an array by appending
[]to the name. - Example handling:
php if (isset($_POST['credit_card'])) { $card = $_POST['credit_card']; switch ($card) { case 'Visa': echo "Visa selected"; break; // ... } } else { echo "Please select a card"; }
Functions
- Define reusable code blocks:
php function happyBirthday(string $name, int $age) { echo "Happy Birthday $name, you are $age years old!"; } happyBirthday('SpongeBob', 30); - Parameters act as local variables; use
returnto send a value back. - Example:
function isEven(int $n): bool { return $n % 2 === 0; }
String Manipulation Functions
strtolower(),strtoupper(),trim(),str_pad(),str_replace(),strrev(),strlen(),strpos(),substr(),implode(),explode().- Useful for formatting usernames, extracting parts of a string, or preparing data for storage.
Sanitizing and Validating User Input
- Sanitization removes unwanted characters:
php $clean = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_SPECIAL_CHARS); - Validation checks format:
php $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); if ($email === false) { echo "Invalid email"; } - Combine
empty()andisset()to ensure required fields are present.
Cookies
- Set a cookie:
php setcookie('favorite_food', 'Pizza', time() + 86400 * 7, '/'); - Delete by setting expiration time in the past.
- Access via
$_COOKIEand iterate withforeach.
Sessions
- Start with
session_start();before any output. - Store data:
$_SESSION['username'] = $username; - Retrieve on any page after calling
session_start();. - End a session with
session_destroy();. - Common use‑case: login system that persists across pages.
Server Super‑Global ($_SERVER)
- Provides request metadata such as
$_SERVER['PHP_SELF'](current script name) and$_SERVER['REQUEST_METHOD']. - Useful for self‑referencing forms and detecting GET vs POST without relying on
isset($_POST['submit']).
Password Hashing
- Create a hash:
$hash = password_hash($password, PASSWORD_DEFAULT); - Verify:
if (password_verify($input, $hash)) { /* login success */ } - Stores only the hash in the database, protecting plain‑text passwords.
MySQL Integration (MySQLi Procedural)
- Connection (
database.php):php $conn = mysqli_connect('localhost', 'root', '', 'businessdb'); if (!$conn) { die('Connection failed'); } - Creating a Table (phpMyAdmin) – define columns, primary key, auto‑increment, appropriate data types (e.g.,
VARCHAR(25)for usernames,CHAR(255)for password hashes). - Inserting Data:
php $sql = "INSERT INTO users (user, password) VALUES (?, ?)"; $stmt = mysqli_prepare($conn, $sql); mysqli_stmt_bind_param($stmt, 'ss', $username, $hash); mysqli_stmt_execute($stmt); - Use prepared statements to prevent SQL injection.
- Retrieving Data:
php $result = mysqli_query($conn, "SELECT * FROM users WHERE user='SpongeBob'"); if (mysqli_num_rows($result) > 0) { $row = mysqli_fetch_assoc($result); echo $row['id']; } - Exception Handling – wrap database operations in
try { ... } catch (mysqli_sql_exception $e) { echo 'Error'; }to avoid exposing raw errors.
Building a Complete Registration Form
- Form fields: username, password (both filtered with
FILTER_SANITIZE_SPECIAL_CHARS). - Validate non‑empty, hash the password, insert into
userstable, handle duplicate‑username errors with atry/catchblock. - Provide user feedback (
You are now registeredorUsername is taken).
Final Thoughts
- This guide walks you from installing a local PHP environment to building fully functional web pages that interact with databases, manage sessions, and handle user input securely.
- Mastery of the basics—variables, control structures, arrays, functions, and super‑globals—provides a solid foundation for more advanced topics such as object‑oriented PHP, MVC frameworks, and API development.
By setting up a local server, mastering PHP syntax, handling forms securely, and integrating MySQL, you now have all the essential tools to build dynamic, data‑driven web applications without needing to watch the original video.