PHP-Fundamentals
PHP-Fundamentals
-- Joining tables (INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN
(emulated))
SELECT * FROM table1 INNER JOIN table2 ON table1.id =
table2.table1_id;
SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.table1_id;
SELECT * FROM table1 RIGHT JOIN table2 ON table1.id =
table2.table1_id;
-- FULL OUTER JOIN (emulated in MySQL, requires UNION)
SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.table1_id
UNION
SELECT * FROM table1 RIGHT JOIN table2 ON table1.id = table2.table1_id
WHERE table1.id IS NULL OR table2.table1_id IS NULL;
-- Creating a table
CREATE TABLE example_table (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Altering a table
ALTER TABLE example_table ADD COLUMN email VARCHAR(255);
ALTER TABLE example_table MODIFY COLUMN age VARCHAR(50);
ALTER TABLE example_table DROP COLUMN email;
-- Dropping a table
DROP TABLE example_table;
-- Creating an index
CREATE INDEX idx_name ON table_name(name);
-- Creating a database
CREATE DATABASE mydatabase;
-- Using a database
USE mydatabase;
-- Deleting a database
DROP DATABASE mydatabase;
-- Creating a view
CREATE VIEW myview AS SELECT column1, column2 FROM table_name WHERE
column3 = 'somevalue';
CALL GetCustomers();
-- Functions (example)
DELIMITER //
CREATE FUNCTION AddNumbers(a INT, b INT) RETURNS INT
DETERMINISTIC
BEGIN
RETURN a + b;
END //
DELIMITER ;
1. String Functions:
CONCAT(str1, str2, ...): Joins two or more strings together.
o Example: SELECT CONCAT('Hello', ' ', 'World'); (Result: Hello World)
SUBSTRING(str, pos, len): Extracts a substring from a string.
o Example: SELECT SUBSTRING('MySQL Tutorial', 1, 5); (Result: MySQL)
LENGTH(str): Returns the length of a string.
o Example: SELECT LENGTH('MySQL'); (Result: 5)
UPPER(str) / LOWER(str): Converts a string to uppercase or lowercase.
o Example: SELECT UPPER('mysql'); (Result: MYSQL)
TRIM(str) / LTRIM(str) / RTRIM(str): Removes leading and/or trailing spaces from a string.
o Example: SELECT TRIM(' MySQL '); (Result: MySQL)
REPLACE(str, from_str, to_str): Replaces all occurrences of a substring within a string.
o Example: SELECT REPLACE('Hello World', 'World', 'MySQL'); (Result: Hello MySQL)
INSTR(str, substr): Returns the position of the first occurrence of a substring within a
string.
o Example: SELECT INSTR('MySQL', 'SQL'); (Result: 3)
2. Numeric Functions:
ABS(num): Returns the absolute value of a number.
o Example: SELECT ABS(-10); (Result: 10)
ROUND(num, decimals): Rounds a number to a specified number of decimal places.
o Example: SELECT ROUND(3.14159, 2); (Result: 3.14)
CEIL(num) / FLOOR(num): Rounds a number up or down to the nearest integer.
o Example: SELECT CEIL(3.2); (Result: 4), SELECT FLOOR(3.8); (Result: 3)
MOD(num1, num2): Returns the remainder of a division.
o Example: SELECT MOD(10, 3); (Result: 1)
RAND(): Generates a random number.
o Example: SELECT RAND();
4. Aggregate Functions:
COUNT(expr): Returns the number of rows that match a specified criterion.
o Example: SELECT COUNT(*) FROM customers;
SUM(expr): Returns the sum of values in a column.
o Example: SELECT SUM(sales) FROM orders;
AVG(expr): Returns the average value of a column.
o Example: SELECT AVG(price) FROM products;
MIN(expr): Returns the minimum value in a column.
o Example: SELECT MIN(age) FROM employees;
MAX(expr): Returns the maximum value in a column.
o Example: SELECT MAX(salary) FROM employees;
6. Other Functions:
VERSION(): Returns the MySQL server version.
DATABASE(): Returns the name of the current database.
USER(): Returns the current MySQL user.
PASSWORD(str): Calculates a password hash (Note: This function is deprecated for
security reasons. Use SHA2() instead).
SHA2(str, hash_length): Calculates a SHA-2 hash value.
These functions are essential for writing efficient and powerful SQL queries. Understanding and
utilizing them effectively allows you to manipulate and analyze data in various ways, making your
database operations more robust.
1. Access phpMyAdmin:
Open your web browser and navigate to your phpMyAdmin URL (usually something like
http://localhost/phpmyadmin or http://yourdomain.com/phpmyadmin).
Log in with your MySQL username and password.
2. Create a Database:
In the left-hand navigation panel, you'll see a list of existing databases.
At the top of the left panel, there's a "New" button, or an input field labeled "Create
database".
Enter a name for your database (e.g., my_library).
Select a collation (e.g., utf8mb4_unicode_ci). Collation determines how characters are
sorted and compared. utf8mb4_unicode_ci is a good general-purpose choice.
Click the "Create" button.
3. Create a Table:
After creating the database, it should be selected in the left-hand panel.
In the main panel, you'll see a section labeled "Create table".
Enter a name for your table (e.g., books).
Specify the number of columns you want (e.g., 4).
Click "Go".
Now, define your table columns:
o Column 1: id
Name: id
Type: INT
Length/Values: (Leave blank or enter a reasonable length)
A_I (Auto Increment): Check this box.
Index: Select PRIMARY.
o Column 2: title
Name: title
Type: VARCHAR
Length/Values: 255 (or another suitable length).
o Column 3: author
Name: author
Type: VARCHAR
Length/Values: 255
o Column 4: publication_year
Name: publication_year
Type: INT
Length/Values: 4
Click "Save".
4. Insert Data:
With the books table selected, click the "Insert" tab at the top of the main panel.
You'll see rows where you can enter data. Leave the id column blank (it will auto-
increment).
Enter data for title, author, and publication_year. For example:
o title: "The Hitchhiker's Guide to the Galaxy"
o author: "Douglas Adams"
o publication_year: 1979
Add another row:
o title: "Pride and Prejudice"
o author: "Jane Austen"
o publication_year: 1813
Add a third row:
o title: "Dune"
o author: "Frank Herbert"
o publication_year: 1965
Click "Go" at the bottom of the page.
5. Verify Data:
Click the "Browse" tab at the top of the main panel.
You should now see the data you inserted in the books table.
Example SQL (for reference):
Here's the equivalent SQL code that phpMyAdmin executed behind the scenes:
SQL
CREATE DATABASE my_library;
USE my_library;
By following these steps, you've successfully created a database, a table, and inserted data
using phpMyAdmin's graphical interface.
Let's break down each of these core PHP concepts with examples and explanations:
1. PHP Fundamentals
Syntax:
o PHP code is embedded within HTML using <?php ... ?>.
o Statements end with a semicolon ;.
o Variables start with $.
o Comments: // (single-line), /* ... */ (multi-line), # (single-line).
Variables:
o Dynamically typed (no need to declare types).
o Example: $name = "John"; $age = 30;
Data Types:
o String, Integer, Float, Boolean, Array, Object, NULL, Resource.
Constants:
o Defined using define().
o Example: define("PI", 3.14159);
Output:
o echo, print.
o Example: echo "Hello, $name!";
Loops:
o for, while, do...while, foreach.
o Example:
PHP
for ($i = 0; $i < 5; $i++) {
echo $i;
}
PHP
$colors = array("red", "green", "blue");
foreach($colors as $color){
echo $color;
}
3. Arrays
Indexed Arrays:
o Example: $colors = array("red", "green", "blue");
o Access: $colors[0].
Associative Arrays:
o Example: $person = array("name" => "John", "age" => 30);
o Access: $person["name"].
Multidimensional Arrays:
o Arrays within arrays.
Array Functions:
o count(), array_push(), array_pop(), array_merge(), sort(), etc.
4. Functions
User-Defined Functions:
o Example:
PHP
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
Function Parameters:
o Passing values to functions.
Return Values:
o Returning results from functions.
Variable Scope:
o Local and global variables.
Built in functions:
o PHP has many built in functions.
5. Forms
HTML Forms:
o <form>, <input>, <select>, <textarea>, etc.
Form Processing:
o $_GET (for GET method), $_POST (for POST method), $_REQUEST.
o Example:
PHP
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
echo "Hello, $name!";
}
Form Validation:
o Checking user input for errors.
o filter_var(), isset(), empty().
6. OOP in PHP
Classes and Objects:
o Blueprint for creating objects.
o Example:
PHP
class Person {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function greet() {
return "Hello, " . $this->name;
}
}
$person = new Person("Bob");
echo $person->greet();
7. Sessions
Session Start:
o session_start().
Session Variables:
o $_SESSION superglobal array.
o Example: $_SESSION["username"] = "john_doe";
Session Management:
o session_destroy(), unset().
Cookies:
o Sessions often rely on cookies to store session IDs.
Security:
o Session hijacking, session fixation.
PHP
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_SESSION["username"] = $_POST["username"];
echo "Welcome, " . $_SESSION["username"] . "!";
}
?>
<form method="post">
<label>Username:</label>
<input type="text" name="username">
<input type="submit" value="Submit">
</form>
<?php
if(isset($_SESSION["username"])){
echo "<br><a href='logout.php'>Logout</a>";
}
?>
<?php //logout.php
session_start();
session_destroy();
echo "Logged out";
?>
This comprehensive overview should give you a solid foundation in PHP. Remember to practice
these concepts by building projects and experimenting with the code.
Let's cover the three topics: MySQL Structure and Syntax, MySQL Functions, and
phpMyAdmin.
2. MySQL Functions
String Functions:
o CONCAT(): Joins strings.
o SUBSTRING(): Extracts substrings.
o LENGTH(): Returns string length.
o UPPER()/LOWER(): Changes case.
o TRIM(): Removes whitespace.
Numeric Functions:
o ABS(): Absolute value.
o ROUND(): Rounds numbers.
o CEIL()/FLOOR(): Rounds up/down.
o MOD(): Modulus.
o RAND(): Random number.
Date and Time Functions:
o NOW(): Current date and time.
o CURDATE(): Current date.
o CURTIME(): Current time.
o DATE_FORMAT(): Formats dates.
o DATE_ADD()/DATE_SUB(): Adds/subtracts intervals.
Aggregate Functions:
o COUNT(): Counts rows.
o SUM(): Calculates sums.
o AVG(): Calculates averages.
o MIN()/MAX(): Finds minimum/maximum values.
Control Flow Functions:
o IF(): Conditional logic.
o CASE: More complex conditional logic.
o COALESCE(): Returns the first non-NULL value.
3. phpMyAdmin
Web-Based Interface:
o A tool for managing MySQL databases through a web browser.
Database Management:
o Creating, deleting, and selecting databases.
Table Management:
o Creating, altering, and deleting tables.
o Adding, editing, and deleting columns.
Data Manipulation:
o Inserting, updating, and deleting data.
o Running SQL queries.
o Browsing tables.
User Management:
o Creating and managing MySQL users.
Import/Export:
o Importing and exporting databases and tables in various formats (SQL, CSV, etc.).
SQL Execution:
o Running custom SQL queries.
Graphical Interface:
o Provides a visual way to perform database tasks without writing SQL.
Ease of Use:
o Simplifies database administration.
Security:
o It is very important to keep your phpmyadmin login secure.
Key Points:
MySQL is a relational database management system (RDBMS).
SQL is the standard language for interacting with MySQL.
phpMyAdmin is a very useful tool for people who are new to MySQL, and for experienced
developers alike.
MySQL functions enhance the capabilities of SQL queries.
Understanding database structure is essential for effective data management.