MySQL, PHP and Databases

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Storing data is the primary reason for using a database.

False (B)

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.

False (B)

The char data type in MySQL allows for flexible string sizes, optimizing storage for varying lengths.

<p>False (B)</p> Signup and view all the answers

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.

<p>True (A)</p> Signup and view all the answers

SQL is primarily a procedural language, focusing on step-by-step instructions to manipulate data.

<p>False (B)</p> Signup and view all the answers

MySQL does not natively support control statements like if or loop within queries.

<p>False (B)</p> Signup and view all the answers

In SQL, keywords are case-sensitive for table and column names.

<p>False (B)</p> Signup and view all the answers

In SQL, NOT NULL constraints dictate that a column can contain missing values.

<p>False (B)</p> Signup and view all the answers

The asterisk (*) in a SELECT query stands for deleting all columns of the specified table.

<p>False (B)</p> Signup and view all the answers

Column aliases in SQL are only for renaming tables, not individual column headings.

<p>False (B)</p> Signup and view all the answers

The CONCAT function in SQL is used to divide column names or strings.

<p>False (B)</p> Signup and view all the answers

String literals in SQL must always be enclosed in double quotes.

<p>False (B)</p> Signup and view all the answers

Using concatenation is useful for calculating totals in different fields in SQL.

<p>False (B)</p> Signup and view all the answers

The DISTINCT keyword in SQL is used to include all duplicate results in a query.

<p>False (B)</p> Signup and view all the answers

The WHERE clause in SQL is used to filter rows based on specified conditions.

<p>True (A)</p> Signup and view all the answers

The BETWEEN operator in SQL is used to specify a single value within a range of two values.

<p>False (B)</p> Signup and view all the answers

In SQL, comparing a column to NULL using the equals (=) operator will always yield true if the column contains a NULL value.

<p>False (B)</p> Signup and view all the answers

The ORDER BY clause in SQL sorts the result set in ascending order by default.

<p>True (A)</p> Signup and view all the answers

In SQL, ASC stands for ascending order, while DEC represents decimal order.

<p>False (B)</p> Signup and view all the answers

The UPDATE command without a WHERE clause modifies all rows in the table.

<p>True (A)</p> Signup and view all the answers

The SQL UPDATE command is primarily used for creating new tables rather than modifying existing data.

<p>False (B)</p> Signup and view all the answers

Using the DELETE command in SQL requires a WHERE cause.

<p>False (B)</p> Signup and view all the answers

Deleting structure and entire tables in an SQL database is easily reversible.

<p>False (B)</p> Signup and view all the answers

DELETE, TRUNCATE, and DROP are all interchangeable commands for removing records from a table.

<p>False (B)</p> Signup and view all the answers

The TRUNCATE command can delete specific rows based on a WHERE clause.

<p>False (B)</p> Signup and view all the answers

A primary key in a database table uniquely identifies each record in that table.

<p>True (A)</p> Signup and view all the answers

A foreign key establishes a link between tables by referencing the primary key of another table.

<p>True (A)</p> Signup and view all the answers

The presence of a foreign key constraint guarantees data consistency between related tables.

<p>True (A)</p> Signup and view all the answers

PDO and MySQLi are database systems.

<p>False (B)</p> Signup and view all the answers

PDO supports only MySQL databases, while MySQLi is versatile and can connect to different database systems.

<p>False (B)</p> Signup and view all the answers

A prepared statement helps prevent SQL injection vulnerabilities by separating SQL logic from data.

<p>True (A)</p> Signup and view all the answers

The die() function in PHP will continue to execute the code, even if there is an error.

<p>False (B)</p> Signup and view all the answers

In PHP, the $mysqli->set_charset() function is used to set the character set for a MySQL connection.

<p>True (A)</p> Signup and view all the answers

In PHP, the fetch_assoc() method fetches a result row as an enumerated array.

<p>False (B)</p> Signup and view all the answers

PDO only supports named parameters in prepared statements for data binding.

<p>False (B)</p> Signup and view all the answers

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.

<p>False (B)</p> Signup and view all the answers

Functions defined within a file included using include_once or require_once can be redefined in the main script.

<p>False (B)</p> Signup and view all the answers

The include and require statements are functionally identical and can be used interchangeably in all cases.

<p>False (B)</p> Signup and view all the answers

Files including using include should contain variables used inside a function block that need to be used by a main PHP page.

<p>False (B)</p> Signup and view all the answers

Flashcards

What is a Database?

A software system used to store, retrieve, and manage data.

What is SQL?

A language designed for managing data held in a relational database management system (RDBMS).

What is Numeric?

A data type representing numeric values.

What is char(size)?

A data type representing fixed-length strings in MySQL.

Signup and view all the flashcards

What is varchar(size)?

A data type representing variable-length strings in MySQL.

Signup and view all the flashcards

What is text in MySQL?

A data type representing a string of text.

Signup and view all the flashcards

What is SELECT?

SQL command used to retrieve data from one or more tables.

Signup and view all the flashcards

What is INSERT?

SQL command used to add new data to a database table.

Signup and view all the flashcards

What is UPDATE?

SQL command used to modify existing data in a database table.

Signup and view all the flashcards

What is DELETE?

SQL command used to remove data from a database table.

Signup and view all the flashcards

What is CREATE DATABASE?

SQL keyword used to create a new database.

Signup and view all the flashcards

What is CREATE TABLE?

SQL keyword used to create a new table in a database.

Signup and view all the flashcards

What are SQL Keywords?

Keywords that are usually capitalized in SQL.

Signup and view all the flashcards

What are Aliases?

Renames a table or column heading and uses the AS keyword.

Signup and view all the flashcards

What is CONCAT?

Operator that is used to join column names or strings together.

Signup and view all the flashcards

What is the WHERE clause?

A clause used to filter rows by specific conditions in SQL.

Signup and view all the flashcards

What is DISTINCT?

Keyword used to retrieve distinct, non-duplicate results in SQL.

Signup and view all the flashcards

What is BETWEEN Operator?

Operator used to specify a range of values in a WHERE clause.

Signup and view all the flashcards

What is NULL?

The value that represents that something is missing/unknown.

Signup and view all the flashcards

What is ORDER BY?

Clause which sorts rows, use ASC or DESC.

Signup and view all the flashcards

What is UPDATE command?

The SQL command to modify field values.

Signup and view all the flashcards

What is SET clause?

Specify the table field.

Signup and view all the flashcards

What can you DROP?

Drops keys, constraints, tables, and databases.

Signup and view all the flashcards

What is TRUNCATE TABLE?

Deletes all entries from a table.

Signup and view all the flashcards

What is FOREIGN KEY?

Creates a connection between tables.

Signup and view all the flashcards

What are PDO & MySQLi?

PHP Extensions: PHP Data Objects and MySQL Improved.

Signup and view all the flashcards

What is mysqli?

A PHP class to connect to MySQL from PHP script.

Signup and view all the flashcards

What does $mysqli = new mysqli() do?

Connects PHP to MySQL.

Signup and view all the flashcards

What does $mysqli->connect_errno do?

Checks the connection.

Signup and view all the flashcards

What does die() do?

Exits the execution.

Signup and view all the flashcards

What is $mysqli->query()?

Executes an SQL query via MySQL connection.

Signup and view all the flashcards

What does fetch_assoc() do?

Gets rows from result set.

Signup and view all the flashcards

What does $mysqli->prepare() do?

Prepared statement with MySQLi.

Signup and view all the flashcards

What does bind_param() do?

Binds parameters to prepared query.

Signup and view all the flashcards

What does execute() do?

Executes the query.

Signup and view all the flashcards

What is PDO?

Used to connect to database.

Signup and view all the flashcards

What is binding?

Binds PHP params to named params.

Signup and view all the flashcards

What is include()?

Includes/evaluates file.

Signup and view all the flashcards

What is require()?

Includes/evaluates or halts on error.

Signup and view all the flashcards

What does include do?

Produces a warning.

Signup and view all the flashcards

What does require do?

Produces a fatal error.

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 to 9999-12-31
  • datetime can range from 1000-01-01 00:00:00 to 9999-12-31 23:59:59
  • timestamp can range from '1970-01-01 00:00:01 UTC to 2038-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 AS No. 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 in SQL use IS NULL:
    • Example: SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL

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.

Quiz Team

Related Documents

More Like This

Use Quizgecko on...
Browser
Browser