0% found this document useful (0 votes)
2 views

PHP-Fundamentals

The document provides a comprehensive guide on MySQL syntax and functions, covering basic SQL operations such as SELECT, INSERT, UPDATE, and DELETE, as well as advanced topics like JOINs, aggregate functions, and stored procedures. It also includes instructions for creating databases and tables using phpMyAdmin, along with examples of PHP fundamentals, flow control, arrays, functions, forms, and object-oriented programming. Overall, it serves as a detailed reference for working with MySQL and PHP.

Uploaded by

annemoises283
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PHP-Fundamentals

The document provides a comprehensive guide on MySQL syntax and functions, covering basic SQL operations such as SELECT, INSERT, UPDATE, and DELETE, as well as advanced topics like JOINs, aggregate functions, and stored procedures. It also includes instructions for creating databases and tables using phpMyAdmin, along with examples of PHP fundamentals, flow control, arrays, functions, forms, and object-oriented programming. Overall, it serves as a detailed reference for working with MySQL and PHP.

Uploaded by

annemoises283
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

CORRECT STRUCTURE AND SYNTAX OF MYSQL


-- Basic SELECT statement: Selecting all columns from a table
SELECT * FROM table_name;

-- Selecting specific columns


SELECT column1, column2, column3 FROM table_name;

-- Filtering rows with a WHERE clause


SELECT * FROM table_name WHERE column1 = 'value';

-- Using comparison operators in WHERE clause


SELECT * FROM table_name WHERE column2 > 10;
SELECT * FROM table_name WHERE column3 != 'other_value';
SELECT * FROM table_name WHERE column4 BETWEEN 1 AND 100;
SELECT * FROM table_name WHERE column5 LIKE 'prefix%'; -- For pattern
matching

-- Using logical operators (AND, OR, NOT)


SELECT * FROM table_name WHERE column1 = 'value' AND column2 > 10;
SELECT * FROM table_name WHERE column1 = 'value' OR column2 > 10;
SELECT * FROM table_name WHERE NOT column1 = 'value';

-- Ordering results with ORDER BY


SELECT * FROM table_name ORDER BY column1 ASC; -- Ascending order
SELECT * FROM table_name ORDER BY column2 DESC; -- Descending order
SELECT * FROM table_name ORDER BY column1 ASC, column2 DESC; --
Multiple columns

-- Limiting the number of results with LIMIT and OFFSET


SELECT * FROM table_name LIMIT 10; -- First 10 rows
SELECT * FROM table_name LIMIT 10 OFFSET 20; -- 10 rows starting from
the 21st row

-- Using aggregate functions (COUNT, SUM, AVG, MIN, MAX)


SELECT COUNT(*) FROM table_name;
SELECT SUM(column2) FROM table_name;
SELECT AVG(column2) FROM table_name;
SELECT MIN(column2) FROM table_name;
SELECT MAX(column2) FROM table_name;

-- Grouping results with GROUP BY


SELECT column1, COUNT(*) FROM table_name GROUP BY column1;
SELECT column1, AVG(column2) FROM table_name GROUP BY column1 HAVING
AVG(column2) > 50; -- Using HAVING to filter groups

-- 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;

-- Inserting data into a table


INSERT INTO table_name (column1, column2, column3) VALUES ('value1',
123, 'value3');

-- Updating data in a table


UPDATE table_name SET column2 = 456 WHERE column1 = 'value1';

-- Deleting data from a table


DELETE FROM table_name WHERE column1 = 'value1';

-- 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';

-- Selecting from a view


SELECT * FROM myview;
-- Stored Procedures (example)
DELIMITER //
CREATE PROCEDURE GetCustomers()
BEGIN
SELECT * FROM Customers;
END //
DELIMITER ;

CALL GetCustomers();

-- Functions (example)
DELIMITER //
CREATE FUNCTION AddNumbers(a INT, b INT) RETURNS INT
DETERMINISTIC
BEGIN
RETURN a + b;
END //
DELIMITER ;

SELECT AddNumbers(5, 10);

Key aspects demonstrated:


 SELECT, FROM, WHERE, ORDER BY, LIMIT, OFFSET: Core data retrieval.
 Aggregate functions: Summarizing data.
 GROUP BY, HAVING: Grouping and filtering grouped data.
 JOIN: Combining data from multiple tables.
 INSERT, UPDATE, DELETE: Data manipulation.
 CREATE TABLE, ALTER TABLE, DROP TABLE: Table management.
 CREATE INDEX: Optimizing queries.
 CREATE DATABASE, USE, DROP DATABASE: Database management.
 CREATE VIEW, selecting from views: Creating and using virtual tables.
 Stored procedures and functions: creating reusable code blocks.
 Correct syntax: Using keywords, parentheses, commas, and semicolons appropriately.
 Data types: Implicitly showing usage of various common data types.
 Comments: Using -- for single-line comments.
 Delimiter: Showing the use of delimiters for stored procedures and functions.

2. DIFFERENT FUNCTIONS USED IN MYSQL


MySQL functions are pre-built routines that perform specific operations on data. They enhance
query capabilities by allowing you to manipulate, transform, and analyze data within your SQL
statements. Here's a summary and explanation of common MySQL functions, categorized by
their purpose:

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();

3. Date and Time Functions:


 NOW() / CURRENT_TIMESTAMP(): Returns the current date and time.
o Example: SELECT NOW();
 CURDATE(): Returns the current date.
o Example: SELECT CURDATE();
 CURTIME(): Returns the current time.
o Example: SELECT CURTIME();
 DATE(datetime) / TIME(datetime): Extracts the date or time part from a datetime value.
o Example: SELECT DATE(NOW());, SELECT TIME(NOW());
 YEAR(date) / MONTH(date) / DAY(date) / HOUR(time) / MINUTE(time) /
SECOND(time): Extracts specific date or time parts.
o Example: SELECT YEAR(NOW());
 DATE_ADD(date, INTERVAL expr unit) / DATE_SUB(date, INTERVAL expr unit): Adds
or subtracts a time interval from a date.
o Example: SELECT DATE_ADD(NOW(), INTERVAL 1 DAY);

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;

5. Control Flow Functions:


 IF(expr, value_if_true, value_if_false): Returns one value if a condition is true, and
another value if it is false.
o Example: SELECT IF(age >= 18, 'Adult', 'Minor');
 CASE WHEN ... THEN ... ELSE ... END: Allows for more complex conditional logic.
o Example: SELECT CASE WHEN age < 18 THEN 'Minor' WHEN age >= 18 AND age <
65 THEN 'Adult' ELSE 'Senior' END;
 COALESCE(value1, value2, ...): Returns the first non-NULL value in a list.
o Example: SELECT COALESCE(NULL, 'MySQL', 'Database'); (Result: MySQL)

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.

3. CREATE A DATABASE AND TABLE, AND INSERT DATA IN


PHPMYADMIN.

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;

CREATE TABLE books (


id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
author VARCHAR(255),
publication_year INT
);

INSERT INTO books (title, author, publication_year) VALUES


('The Hitchhiker''s Guide to the Galaxy', 'Douglas Adams', 1979),
('Pride and Prejudice', 'Jane Austen', 1813),
('Dune', 'Frank Herbert', 1965);

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!";

2. Flow Control and Looping


 Conditional Statements:
o if, elseif, else, switch.
o Example:
PHP
$age = 20;
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}

 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();

 Properties and Methods:


o Attributes and functions of a class.
 Constructors and Destructors:
o __construct(), __destruct().
 Inheritance:
o Extending classes.
 Encapsulation:
o Controlling access to properties and methods (public, protected, private).
 Polymorphism:
o Objects of different classes can be treated as objects of a common type.
 Interfaces and Traits:
o Ways to create reusable code.

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.

Example (Session and Form):

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.

1. MySQL Structure and Syntax


 Databases:
o A container for tables.
o Created with CREATE DATABASE database_name;.
o Selected with USE database_name;.
 Tables:
o Store data in rows and columns.
o Created with CREATE TABLE table_name (column1 data_type, column2 data_type, ...);.
o Columns have names and data types (INT, VARCHAR, DATE, etc.).
 SQL (Structured Query Language):
o The language used to interact with MySQL.
 Basic SQL Statements:
o SELECT: Retrieves data.
 SELECT column1, column2 FROM table_name WHERE condition;.
 SELECT * FROM table_name; (selects everything)
o INSERT: Adds new rows.
 INSERT INTO table_name (column1, column2) VALUES (value1, value2);.
o UPDATE: Modifies existing rows.
 UPDATE table_name SET column1 = new_value WHERE condition;.
o DELETE: Removes rows.
 DELETE FROM table_name WHERE condition;.
o JOIN: Combines data from multiple tables.
 SELECT * FROM table1 JOIN table2 ON table1.id = table2.table1_id;.
o WHERE: Filters rows based on conditions.
o ORDER BY: Sorts results.
o GROUP BY: Groups rows with the same values.
o LIMIT: Restricts the number of rows returned.
 Primary Keys:
o Uniquely identify each row in a table.
 Foreign Keys:
o Establish relationships between tables.
 Indexes:
o Improve query performance.

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.

You might also like