Podcast
Questions and Answers
Storing data is the primary reason for using a database.
Storing data is the primary reason for using a database.
False (B)
In the client-server model, the SQL server directly accesses the clients.
In the client-server model, the SQL server directly accesses the clients.
False (B)
The decimal
data type is used to represent arbitrary values in MySQL.
The decimal
data type is used to represent arbitrary values in MySQL.
False (B)
The char
data type in MySQL allows for flexible string sizes, optimizing storage for varying lengths.
The char
data type in MySQL allows for flexible string sizes, optimizing storage for varying lengths.
The timestamp
data type in MySQL has a range from '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
The timestamp
data type in MySQL has a range from '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
SQL is primarily a procedural language, focusing on step-by-step instructions to manipulate data.
SQL is primarily a procedural language, focusing on step-by-step instructions to manipulate data.
MySQL does not natively support control statements like if
or loop
within queries.
MySQL does not natively support control statements like if
or loop
within queries.
In SQL, keywords are case-sensitive for table and column names.
In SQL, keywords are case-sensitive for table and column names.
In SQL, NOT NULL
constraints dictate that a column can contain missing values.
In SQL, NOT NULL
constraints dictate that a column can contain missing values.
The asterisk (*) in a SELECT
query stands for deleting all columns of the specified table.
The asterisk (*) in a SELECT
query stands for deleting all columns of the specified table.
Column aliases in SQL are only for renaming tables, not individual column headings.
Column aliases in SQL are only for renaming tables, not individual column headings.
The CONCAT
function in SQL is used to divide column names or strings.
The CONCAT
function in SQL is used to divide column names or strings.
String literals in SQL must always be enclosed in double quotes.
String literals in SQL must always be enclosed in double quotes.
Using concatenation is useful for calculating totals in different fields in SQL.
Using concatenation is useful for calculating totals in different fields in SQL.
The DISTINCT
keyword in SQL is used to include all duplicate results in a query.
The DISTINCT
keyword in SQL is used to include all duplicate results in a query.
The WHERE
clause in SQL is used to filter rows based on specified conditions.
The WHERE
clause in SQL is used to filter rows based on specified conditions.
The BETWEEN
operator in SQL is used to specify a single value within a range of two values.
The BETWEEN
operator in SQL is used to specify a single value within a range of two values.
In SQL, comparing a column to NULL using the equals (=) operator will always yield true if the column contains a NULL value.
In SQL, comparing a column to NULL using the equals (=) operator will always yield true if the column contains a NULL value.
The ORDER BY
clause in SQL sorts the result set in ascending order by default.
The ORDER BY
clause in SQL sorts the result set in ascending order by default.
In SQL, ASC
stands for ascending order, while DEC
represents decimal order.
In SQL, ASC
stands for ascending order, while DEC
represents decimal order.
The UPDATE
command without a WHERE
clause modifies all rows in the table.
The UPDATE
command without a WHERE
clause modifies all rows in the table.
The SQL UPDATE
command is primarily used for creating new tables rather than modifying existing data.
The SQL UPDATE
command is primarily used for creating new tables rather than modifying existing data.
Using the DELETE
command in SQL requires a WHERE
cause.
Using the DELETE
command in SQL requires a WHERE
cause.
Deleting structure and entire tables in an SQL database is easily reversible.
Deleting structure and entire tables in an SQL database is easily reversible.
DELETE
, TRUNCATE
, and DROP
are all interchangeable commands for removing records from a table.
DELETE
, TRUNCATE
, and DROP
are all interchangeable commands for removing records from a table.
The TRUNCATE
command can delete specific rows based on a WHERE
clause.
The TRUNCATE
command can delete specific rows based on a WHERE
clause.
A primary key in a database table uniquely identifies each record in that table.
A primary key in a database table uniquely identifies each record in that table.
A foreign key establishes a link between tables by referencing the primary key of another table.
A foreign key establishes a link between tables by referencing the primary key of another table.
The presence of a foreign key constraint guarantees data consistency between related tables.
The presence of a foreign key constraint guarantees data consistency between related tables.
PDO and MySQLi are database systems.
PDO and MySQLi are database systems.
PDO supports only MySQL databases, while MySQLi is versatile and can connect to different database systems.
PDO supports only MySQL databases, while MySQLi is versatile and can connect to different database systems.
A prepared statement helps prevent SQL injection vulnerabilities by separating SQL logic from data.
A prepared statement helps prevent SQL injection vulnerabilities by separating SQL logic from data.
The die()
function in PHP will continue to execute the code, even if there is an error.
The die()
function in PHP will continue to execute the code, even if there is an error.
In PHP, the $mysqli->set_charset()
function is used to set the character set for a MySQL connection.
In PHP, the $mysqli->set_charset()
function is used to set the character set for a MySQL connection.
In PHP, the fetch_assoc()
method fetches a result row as an enumerated array.
In PHP, the fetch_assoc()
method fetches a result row as an enumerated array.
PDO only supports named parameters in prepared statements for data binding.
PDO only supports named parameters in prepared statements for data binding.
The include
statement halts the execution of the script if the specified file is not found, while require
generates a warning but continues the execution.
The include
statement halts the execution of the script if the specified file is not found, while require
generates a warning but continues the execution.
Functions defined within a file included using include_once
or require_once
can be redefined in the main script.
Functions defined within a file included using include_once
or require_once
can be redefined in the main script.
The include
and require
statements are functionally identical and can be used interchangeably in all cases.
The include
and require
statements are functionally identical and can be used interchangeably in all cases.
Files including using include
should contain variables used inside a function block that need to be used by a main PHP page.
Files including using include
should contain variables used inside a function block that need to be used by a main PHP page.
Flashcards
What is a Database?
What is a Database?
A software system used to store, retrieve, and manage data.
What is SQL?
What is SQL?
A language designed for managing data held in a relational database management system (RDBMS).
What is Numeric?
What is Numeric?
A data type representing numeric values.
What is char(size)?
What is char(size)?
Signup and view all the flashcards
What is varchar(size)?
What is varchar(size)?
Signup and view all the flashcards
What is text in MySQL?
What is text in MySQL?
Signup and view all the flashcards
What is SELECT?
What is SELECT?
Signup and view all the flashcards
What is INSERT?
What is INSERT?
Signup and view all the flashcards
What is UPDATE?
What is UPDATE?
Signup and view all the flashcards
What is DELETE?
What is DELETE?
Signup and view all the flashcards
What is CREATE DATABASE?
What is CREATE DATABASE?
Signup and view all the flashcards
What is CREATE TABLE?
What is CREATE TABLE?
Signup and view all the flashcards
What are SQL Keywords?
What are SQL Keywords?
Signup and view all the flashcards
What are Aliases?
What are Aliases?
Signup and view all the flashcards
What is CONCAT?
What is CONCAT?
Signup and view all the flashcards
What is the WHERE clause?
What is the WHERE clause?
Signup and view all the flashcards
What is DISTINCT?
What is DISTINCT?
Signup and view all the flashcards
What is BETWEEN Operator?
What is BETWEEN Operator?
Signup and view all the flashcards
What is NULL?
What is NULL?
Signup and view all the flashcards
What is ORDER BY?
What is ORDER BY?
Signup and view all the flashcards
What is UPDATE command?
What is UPDATE command?
Signup and view all the flashcards
What is SET clause?
What is SET clause?
Signup and view all the flashcards
What can you DROP?
What can you DROP?
Signup and view all the flashcards
What is TRUNCATE TABLE?
What is TRUNCATE TABLE?
Signup and view all the flashcards
What is FOREIGN KEY?
What is FOREIGN KEY?
Signup and view all the flashcards
What are PDO & MySQLi?
What are PDO & MySQLi?
Signup and view all the flashcards
What is mysqli?
What is mysqli?
Signup and view all the flashcards
What does $mysqli = new mysqli() do?
What does $mysqli = new mysqli() do?
Signup and view all the flashcards
What does $mysqli->connect_errno do?
What does $mysqli->connect_errno do?
Signup and view all the flashcards
What does die() do?
What does die() do?
Signup and view all the flashcards
What is $mysqli->query()?
What is $mysqli->query()?
Signup and view all the flashcards
What does fetch_assoc() do?
What does fetch_assoc() do?
Signup and view all the flashcards
What does $mysqli->prepare() do?
What does $mysqli->prepare() do?
Signup and view all the flashcards
What does bind_param() do?
What does bind_param() do?
Signup and view all the flashcards
What does execute() do?
What does execute() do?
Signup and view all the flashcards
What is PDO?
What is PDO?
Signup and view all the flashcards
What is binding?
What is binding?
Signup and view all the flashcards
What is include()?
What is include()?
Signup and view all the flashcards
What is require()?
What is require()?
Signup and view all the flashcards
What does include do?
What does include do?
Signup and view all the flashcards
What does require do?
What does require do?
Signup and view all the flashcards
Study Notes
- MySQL and PHP are to be covered
- The course is from the University of Halabja, College of Science, Department of Computer
- Bashdar A. MOHAMMED prepared this lesson on April 7, 2025
Table of Contents
- Discusses Databases
- Discusses introduction Structured Query Language(SQL)
- Topics include how to SELECT, INSERT, UPDATE and DELETE
- Discusses using MySQL and PHP
Table of Contents
- Database introductions occur
- Shows the interaction between a browser, internet, server, web server, file, PHP and database
Data Storage
- Storing data is not the primary reason to use a database
- Flat storage eventually runs into issues with Size, Ease of updating, accuracy, security, redundancy and importance
Database Engine Flow
- SQL Server uses the Client-Server Model
- Clients make a Query to the Engine which then Accesses the Database
Datatypes with MySQL
- Numeric datatypes can be integers with different data sizes
- Numeric datatypes can also represent real numbers such as float, double and decimal
- String datatypes include char(size) which are fixed string lengths
- varchar(size) is a variable size string
- Text data blocks have datatypes called text, tinytext, mediumtext and longtext
- Binary datatypes include binary(size), varbinary(size) which are fixed and variable string lengths respectively
- Date and time have datatypes such as date which can range from
1000-01-01
to9999-12-31
- datetime can range from
1000-01-01 00:00:00
to9999-12-31 23:59:59
- timestamp can range from '
1970-01-01 00:00:01
UTC to2038-01-19 03:14:07
UTC
Structured Query Language(SQL)
- Structured Query Language acronym SQL
- Used as the declarative language when working with relational data
- Formatted in regular English as much as possible
- MySQL dialect support definition, manipulation, and access control of records
- Also support control statements such as if statements or loops
- Designed for writing logic inside the DataBase
SQL Examples
- SELECT first_name, last_name, job_title FROM employees
- SELECT * FROM projects WHERE start_date = '1/1/2006'
- INSERT INTO projects(name, start_date) VALUES('Introduction to MySQL', '1/1/2006')
- UPDATE projects SET end_date = '8/31/2006' WHERE start_date = '1/1/2006'
- DELETE FROM projects WHERE start_date = '1/1/2006'
SQL Queries
- SQL allows communication with the database engine
- Queries provide greater control and flexibility to create a database with SQL
- SQL Keywords are traditionally capitalized
- CREATE DATABASE people(Database name)
Table Creation in SQL
- CREATE TABLE employees (id int NOT NULL, email varchar(50) NOT NULL, first_name varchar(50),last_name varchar(50))
Retrieving entries with SQL
- Retrieve all columns from departments table example "SELECT * FROM departments"
- Retrieve specific columns example "SELECT department_id, name FROM departments"
Column Aliases
- Aliases rename a table or column heading
- Example: SELECT employee_id AS id, first_name, last_name FROM employees
- Can also be used to shorten field or add clarification
- Example: SELECT c.duration, c.ACG AS 'Access Control Gateway' FROM Calls AS c
Concatenation Operation
- Column names or strings can be concatenated with CONCAT
- Enclose string literals in single or double quotes
- Table and column names containing special symbol use "" or ''
- Example: SELECT CONCAT(first_name, ' ', last_name) AS
Full Name
, employee_id ASNo.
FROM employees
Employee Summary
- Goal is to find information about all employees, and list their full name, job title and salary
- Concatenation displays the first and last names as one field
- SELECT CONCAT(first_name, ' ', last_name) AS
Full Name
, job_title, salary FROM employees
Filtering Selection with SQL
- DISTINCT is used to eliminate duplicate results
- Example: SELECT DISTINCT department_id FROM employees
- WHERE clause is used to filter rows by specific conditions
- Example: SELECT last_name, department_id FROM employees WHERE department_id = 1
Comparison Condition
- Conditions can be combined with NOT, OR, and AND with brackets
- Example: SELECT last_name FROM employees WHERE NOT (manager_id = 3 OR manager_id = 4)
- BETWEEN operations can specify a range
- Example: SELECT last_name, salary FROM employees WHERE salary BETWEEN 20000 AND 22000
- IN / NOT IN to specify a set of values
- Example: SELECT first_name, last_name, manager_id FROM employees WHERE manager_id IN (109, 3, 16)
Comparing with NULL
- NULL is a special value which signifies a missing value
- NULL is not the same as zero or a blank space
- To check for
NULL
values inSQL
useIS NULL
:- Example:
SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL
- Example:
Sorting with ORDER BY Clause
- An ORDER BY clause sorts rows
- ASC sorts values by ascending order
- DESC sorts vcalues by descending order
- Example: SELECT last_name, hire_date FROM employees ORDER BY hire_date DESC
Inserting Data
- Insert a new employee such as INSERT INTO employees(email, first_name, last_name) VALUES ('[email protected]', 'Radina', 'Georgieva')
Updating table
- The SQL UPDATE command can update table values
- Ensure to use the WHERE cause, such as UPDATE employees SET last_name = 'Brown' WHERE id = 1
Examples of updating Data
- Update existing post - change title
- UPDATE posts SET title = 'Title Updated!' WHERE id = 2;
- Update existing post - change date
- UPDATE posts SET date = STR_TO_DATE('31-12-2018', '%d-%m-%Y') WHERE YEAR(date) = 2018;
Update Projects tips
- To mark all unfinished projects as being completed today, ensure your end_date is set to Null
- UPDATE projects SET end_date = '2017-01-23' WHERE end_date IS NULL
Deleting Data
- SQL command DELETE FROM employees WHERE id = 6 can be used to delete rows from a table
- Ensure you use the WHERE clause, otherwise all data from the table may be deleted
- Example: DELETE FROM employees WHERE first_name = 'Hristo';
Deleting Databases items
- Structures can be deleted such as keys, constraints tables and entire datasets
- Ensure these actions are used with caution, as they cannot be undone
Dropping, Deleting and Truncating
- Delete entries in a table such as "DELETE FROM employees" or "TRUNCATE TABLE employees"
- Drop a table: DROP TABLE employees
- Drop a Databse: DROP DATABASE people
Setting up
- To setup the database, use commands such as CREATE TABLE drivers(id INT PRIMARY KEY,name VARCHAR(50));
- CREATE TABLE cars(id INT PRIMARY KEY, driver_id INT UNIQUE, CONSTRAINT fk_cars_drivers FOREIGN KEY (driver_id) REFERENCES drivers(id));
Foreign Keys
- FOREIGN KEY (driver_id) REFERENCES drivers(id)
- fk_cars_drivers : Constraint name
- drivers : referent Table
- primary Key : primary Key
MySQLi vs PDO
- PHP Data Objects (PDO) and MySQL Improved (MySQLi) are both PHP extensions that allow PHP developers to interact with MySQL databases.
- PDO provides a versatile and consistent approach to multiple database systems due to its prepared statements
- MySQLi is tailored for MySQL databases and provides both procedural and object-oriented interfaces
- The choice between PDO and MySQLi depends on factors such as personal preference, project requirements, and compatibility with existing codebases.
MySQL in PHP Connections
- Use mysqli class to connect to MySQL from PHP script
- Example: $host = 'localhost'; $user = 'root'; $pass = ''; $db = 'blog'; $mysqli = new mysqli($host, $user, $pass, $db);
- $mysqli->set_charset("utf8")
- die is similar to echo $ print but exits the execution
MysQL in PHP
- $result = $mysqli->query('SELECT * FROM posts');
- if (!$result) die('Cannot read
posts
table');
Fetch Records
- Process the returned result set (table rows / records)
- $title = $row[ title'];
- $content = $row['content'];
Prepared Statement
- Example: deletePost($mysqli, $id) { $statement = $mysqli->prepare("DELETE FROM posts WHERE id = ?"); $statement->bind_param("i", $id); $statement->execute(); return $statement->affected_rows > 0; }
- s = string
- i = integer
- d = double
PDO
- $host = "localhost";
- $db = "erp_system";
- $user = "root";
- Note: always put the connection code in a separate file.
Connect and process Queues
- Try{ $db = new PDO('mysql:host=localhost;dbname=test',$user, $pass); $result = $db->query('SELECT * FROM Users', PDO::FETCH_ASSOC); foreach ($result as $row) {
- print_r($row); }
- Always null out the results
Prepared Statements
- $stmt = $db->prepare("SELECT * FROM Users WHERE fname = ?"); if ($stmt->execute(array($_GET['fname']))) print "Error!: ". $e->getMessage(). "";
Bind parameters
$stmt->bindParam(1, $fname); $stmt->bindParam(2, $lname);
PDO INSERT Statement
- $fname = 'Joro'; $lname = 'Petrov'; $stmt->execute(); $fname = 'Vasil'; $lname = 'Georgiev'; $stmt->execute();
PDO Named Parameter INSERT
- $stmt->execute(["fname" => "Azad" "Iname"=> "Kamaran"]);
Including and Requiring
- include and require load and evaluate a file holding PHP code
- header.php has echo...
- footer.php has echo...
- conn.php has $db = new PDO(...);
- Main.php require "conn.php"; require "header.php"; , echo "page body"; and include "footer.php";
- If a file is not found include produces a warning. require produces a fatal error
Require_once vs Include_once
- require "header.php"; function test(); echo "Page body"; include "header.php";
- Results in "Fatal error: Cannot redeclare test()..."
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.