Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views9 pages

Chapter 5

Uploaded by

u577116577528
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views9 pages

Chapter 5

Uploaded by

u577116577528
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Chapter 5 : Database handling using php with mysql

What is MySQL?
MySQL is an open-source relational database management system (RDBMS). It is the most popular database
system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation.
 The data in a MySQL database are stored in tables which consists of columns and rows.
 MySQL is a database system that runs on a server.
 MySQL is ideal for both small and large applications.
 MySQL is very fast, reliable, and easy to use database system.It uses standard SQL
 MySQL compiles on a number of platforms.

Database Terms:
Database terminology encompasses the terms used to describe the structure, components, and processes of a
database. Key terms include tables, rows, columns, keys, and queries. These terms are essential for understanding
how data is organized, accessed, and manipulated within a database system.
Database:
A structured collection of data, organized for efficient access and management.
Table:
A two-dimensional structure used to store data, resembling a spreadsheet with rows and columns.
Column:
A vertical column in a table, representing a specific type of data (e.g., "name", "age", "city").
Row:
A horizontal row in a table, representing a single record or entry (e.g., a customer's information).
Key:
A column or set of columns used to uniquely identify rows in a table.
Primary Key:
A unique identifier for each record in a table, ensuring no two rows are identical.
Foreign Key:
A column in one table that refers to the primary key of another table, establishing a relationship between the
tables.
Constraint:
A rule that defines the allowable values for a column or set of columns, ensuring data integrity.

Data Types
1. Numeric Data Types
Numeric data types are fundamental to database design and are used to store numbers, whether they are integers,
decimals, or floating-point numbers. These data types allow for mathematical operations
like addition, subtraction, multiplication, and division, which makes them essential for managing financial,
scientific, and analytical data.

2. Character and String Data Types


Character data types are used to store text or character-based data. The choice between fixed-length and
variable-length data types depends on the nature of your data.

3. Date and Time Data Type


SQL provides several data types for storing date and time information. They are essential for managing
timestamps, events, and time-based queries. These are given in the below table.
4. Binary Data Types in SQL
Binary data types are used to store binary data such as images, videos, or other file types. These include:

5. Boolean Data Type in SQL


The BOOLEAN data types are used to store logical values, typically TRUE or FALSE. It's commonly used for
flag fields or binary conditions.

6. Special Data Types


SQL also supports some specialized data types for advanced use cases:

Using mysql client and using phpmyadmin

Both MySQL clients and phpMyAdmin are used to interact with MySQL databases, but they serve different
purposes. MySQL clients are command-line tools, while phpMyAdmin provides a web-based interface.
MySQL Clients:
Purpose:
Used to interact with a MySQL server using the command line. They allow you to execute SQL queries, manage
databases, tables, and users.
Example:
The mysql command-line client.
Benefits:
More powerful and versatile for complex tasks, especially when scripting automation.
Drawbacks:
Requires command-line familiarity and can be less user-friendly for beginners.
phpMyAdmin:
Purpose:
A web-based graphical user interface (GUI) for managing MySQL databases. It allows you to create, modify,
query, and drop tables through a browser interface.
Benefits:
Easier to use for beginners, especially for basic tasks like database administration.
Drawbacks:
Less powerful for complex operations and may not be suitable for scripting automation.
Example:
You can access phpMyAdmin through a web browser, often at an address like http://localhost/phpmyadmin.
In Summary:
Choose MySQL clients for:
Automated tasks, command-line scripting, and when you need more control over the process.
Choose phpMyAdmin for:
Easier database administration, especially for beginners, and when you prefer a GUI interface.
When to use which:
 When scripting database operations: MySQL clients are often preferred for automation.
 When managing databases through a web interface: phpMyAdmin is the standard choice.
 When learning MySQL: phpMyAdmin can be a good starting point due to its user-friendly interface.
Mysql Commands
Data Definition Language (DDL) - Modifying the database structure:
 CREATE DATABASE: Creates a new database.
 CREATE TABLE: Creates a new table within a database.
 ALTER TABLE: Modifies an existing table's structure (e.g., adding, deleting, or changing columns).
 DROP TABLE: Deletes a table from the database.
 RENAME TABLE: Renames a table.
 TRUNCATE TABLE: Deletes all data from a table, but keeps the table structure.
 DROP DATABASE: Deletes a database and all its tables.
 CREATE TABLE AS: Creates a new table with a copy of the data from an existing table.

Data Manipulation Language (DML) - Manipulating data within tables:


 SELECT: Extracts data from a database.
 INSERT INTO: Inserts new data into a table.
 UPDATE: Modifies existing data in a table.
 DELETE: Removes data from a table based on specified conditions.

Data Query Language (DQL) - Retrieving data:


 SELECT (with various clauses):
o WHERE: Filters rows based on conditions.
o ORDER BY: Sorts the result set.
o GROUP BY: Groups rows with the same values in a specified column.
o HAVING: Filters groups based on conditions.
o JOIN: Combines rows from two or more tables based on a related column.

Data Control Language (DCL) - Managing user privileges:


 GRANT: Assigns privileges to users or roles.
 REVOKE: Removes privileges from users or roles.

Transaction Control Language (TCL) - Managing transactions:


 BEGIN TRANSACTION: Starts a new transaction.
 COMMIT: Saves the changes made during a transaction.
 ROLLBACK: Reverts the changes made during a transaction.

Other useful commands:


 SHOW DATABASES: Lists all databases on the server.
 USE [database_name]: Selects a database to work with.
 SHOW TABLES: Lists tables within the currently selected database.
 DESCRIBE [table_name]: Displays the structure (columns, data types, etc.) of a table.
 SHOW CREATE TABLE [table_name]: Shows the SQL statement used to create a specific table.
 SHOW PROCESSLIST: Displays the current active connections and queries.
 \h or \help: Displays help information.
 \q: Quits the current database session.

MySQL Function in PHP


In PHP Scripting language many functions are available for MySQL Database connectivity and executing SQL
queries.
MySQLi is extension in PHP scripting language which gives access to the MYSQL database. MySQLi extension
was introduced version 5.0.0,
The MySQLi extension contains the following important functions which are related to MySQL database
connectivity and management.
● Mysqli_connect() Function
● Mysqli_close() Function
● Mysqli_query()Function

Database Connections:
Before accessing MySQL Database, connect to Database Server machine via PHP scripting language using
Mysqli_connect() Function.

Syntax:
mysqli_connect(“Server Name “,”User Name”,”Password”,”DB Name”);
This function requires four parameters to connect to database server. Database Server name, Database username,
password and Database Name.

Managing Database Connections


The below code describes managing database connection methods and features.
<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;

$DB_name = “School_DB”;

$conn = mysqli_connect($servername, $username, $password,$DB_name);

if (!$conn) {
die(“Connection failed: “ . mysqli_connect_error());
}
echo “Connected successfully”;
?>

In the above code snippet, four variables are used to connect to the Database server. They are
● $servername -> Database Server Server IP address
● $username -> Database Server User Name
● $password -> Database Server Password
● $DB_Name -> Database Name
The mysqli_connect function uses these variables to connect Database server to PHP. If connection gets fail, output
will be printed with MySQL error code. Otherwise connection is success.

Performing Queries
The main goal of MySQL and PHP connectivity is to retrieve and manipulate the data from MySQL database
server. The SQL query statements help in PHP MySQL extension to achieve the objective of MySQL and PHP
connection. “mysqli_query” is a function, that helps to execute the SQL query statements in PHP scripting
language.

Syntax:
mysqli_query(“Connection Object”,”SQL Query”)

Example:
$con=mysqli_connect(“localhost”,”my_user”,”my_password”,”Student_DB “);
$sql=”SELECT student_name,student_age FROM student”;mysqli_query($con,$sql);

Closing Connection:
mysqli_close() Function is used to close an existing opened database connection between PHP scripting and
MySQL Database Server.

Syntax:
mysqli_close(“Connection Object”);

Example:
<?php
$con=mysqli_connect(“localhost”,”$user”,”$password”,”SCHOOL_DB”);
mysqli_close($con);
?>

Example of PHP and MySQL Program:


<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “school_DB”;
$connection = mysqli_connect(‘$servername ‘, ‘$username’, ‘$password’,’$dbname’);
if (mysqli_connect_errno())
{
echo “Failed to connect to MySQL: “ . mysqli_connect_error();
}
sql_stmt = “SELECT * FROM my_contacts”; //SQL select query
$result = mysqli_query($connection,$sql_stmt);//execute SQL statement
$rows = mysqli_num_rows($result);// get number of rows returned
if ($rows)
{
while ($row = mysqli_fetch_array($result))
{
echo ‘ID: ‘ . $row[‘id’] . ‘<br>’;
echo ‘Full Names: ‘ . $row[‘full_names’] . ‘<br>’;
echo ‘Gender: ‘ . $row[‘gender’] . ‘<br>’;
echo ‘Contact No: ‘ . $row[‘contact_no’] . ‘<br>’;
echo ‘Email: ‘ . $row[‘email’] . ‘<br>’;
echo ‘City: ‘ . $row[‘city’] . ‘<br>’;
echo ‘Country: ‘ . $row[‘country’] . ‘<br><br>’;
}
}
mysqli_close($connection); //close the database connection
?>
In the above code the SQL query retrieves two records from student table in school database. These records are
populated into client browser using PHP scripting language.

PHP Database Connection


Connecting to a database in PHP is a crucial step in web development that allows PHP applications to interact with
database systems. By establishing a connection, developers can perform various database operations, such as
storing, retrieving, updating, and deleting data.

To connect to a MySQL database using PHP's MySQL Improved (MySQLi) extension, you can follow these steps:

1. Set up the database credentials


$servername = "localhost"; // Replace with your server name
$username = "your_username"; // Replace with your MySQL username
$password = "your_password"; // Replace with your MySQL password
$dbname = "your_database_name"; // Replace with your database name

2. Create a connection object:


$conn = new mysqli($servername, $username, $password, $dbname);

3. Check the connection:


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

4. Perform database operations: You can now execute SQL queries, fetch results, and perform CRUD
operations on the database using the $conn object. Here's an example of executing a simple query to fetch
data from a table:
$sql = "SELECT * FROM your_table_name";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// Loop through the fetched data
while ($row = $result->fetch_assoc()) {
// Process each row of data
echo "Name: " . $row["name"] . ", Age: " . $row["age"] . "<br>";
}
} else {
echo "No records found.";
}

5. Close the connection: It's important to close the connection when you're done working with the database to
release resources:
$conn->close();

Execute an SQL query and fetch results using PHP


We can perform a query against the database using the PHP mysqli_query() method.

Syntax: We can use the mysqli_query( ) method in two ways:


 Object-oriented style
 Procedural style

Parameters:
 connection: It is required that specifies the connection to use.
 query: It is also required that specifies the database query.
 result mode: It is optional to use.
 Return value: For SELECT, SHOW, DESCRIBE, or EXPLAIN it returns a mysqli_result object. For
other successful queries, it returns true. Otherwise, it returns false on failure.
 Let's understand how we can execute an SQL query.
 Executing an SQL query: We will understand how we can execute an SQL query with an example. We
will create a database, table and then insert some values into it.
 Example: Create a database and insert some values into it.
<?php
$servername = "localhost";
$username = "root";
$password = "";

$conn = new mysqli($servername, $username, $password);


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "CREATE DATABASE gfgDB";


if ($conn->query($sql) === TRUE) {
echo "Database has been created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>

Creating the table:


<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfgDB";

$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "CREATE TABLE Emp (


id INT(6) AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL
)";

if ($conn->query($sql) === TRUE) {


echo "Table has been created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

Inserting some values into the table "Emp":


<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfgDB";

$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Emp (firstname, lastname)
VALUES ('XYZ', 'ABC')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
}else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Fetching results from the database:


<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gfgDB";

$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM Emp";


$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: "
. $row["firstname"]. " " . $row["lastname"]. "<br>";
}
}
else {
echo "No records has been found";
}
$conn->close();
?>

You might also like