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

Php Unit Iiimb

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

Php Unit Iiimb

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

UNIT III - PHP

Using MySQL: MySQL Database - Managing the Database - Backing up


and Restoring Data - Advanced SQL.Getting PHP to talk to MySQL: The
process-querying the database with PHP functions - Using PEAR. Working
with Forms: Building a form - Templates.

MySQL Database

MySQL is the most popular database system used with PHP.

 MySQL is a database system used on the web that runs on a server


 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL is developed, distributed, and supported by Oracle
Corporation

Two ways to communicate with MySQL:

 the command line


 phpMyAdmin.

Accessing the Database from the Command Line

One way of communicating with MySQL is through the MySQL command-


line client.

Type cmd from the Run dialog

Once you reach the command line, type mysqlcommand

mysql -h hostname -u user –p


Prompts

At the MySQL prompt, we can enter database commands followed by enter


key,

For a list of these commands,


Type help or \h at the mysql>prompt.

Command prompt meanings

Commands

Commands that are available at the MySQL prompt.

To display the available databases, type:

mysql> SHOW DATABASES;

which returns:

+----------+
| Database |
+----------+
| mysql |
+----------+
1 rows in set (0.00 sec)

To connect to the mysqldatabase, type the following at the MySQL prompt:


USE MB;

This returns:
Database changed

Managing the Database


Connected to the database, we can create users, databases, and
tables.
To create users above and beyond the default privileged root user, issue the
grantcommand. The grant command uses this syntax:
GRANT PRIVILEGES ON DATABASE.OBJECTS
TO'username'@'hostname' IDENTIFIED BY
'password';

For example:

GRANT ALL PRIVILEGES ON *.* TO 'michele'@'localhost'


IDENTIFIED BY 'secret';

This creates the user michele who can access anything locally. To change to
the michele user, at the mysql command prompt, type:

exit
Then start MySQL from the command line with the new username and
password.The syntax for specifying the username and password when
starting MySQL is:

mysql -h hostname -u username –ppassword

Notice that there is no space between –p and password.

Backing Up and Restoring Data

It is important to back up your databases so that you can recover your data
and be up and running again in case problems occur, such as system crashes,
hardware failures, or users deleting data by mistake.

Backups are also essential as a safeguard before upgrading a MySQL


installation, and they can be used to transfer a MySQL installation to
another system or to set up replica servers.
different types of backups.

Physical (Raw) Versus Logical Backups

Physical backups consist of raw copies of the directories and files that store
database contents. This type of backup is suitable for large, important
databases that need to be recovered quickly when problems occur.

Logical backups save information represented as logical database structure


(CREATE DATABASE, CREATE TABLE statements) and content
(INSERT statements or delimited-text files). This type of backup is suitable
for smaller amounts of data where you might edit the data values or table
structure, or recreate the data on different machine architecture.
To back up only a single table from a database, simply add the table name after
the database name. For example, this command illustrates how to back up only
the authors table:

$ mysqldump -u root -p store authors > authors.sql

Most of the time, you’ll just want to back up everything in the database. To do
this,use the --all-databases command-line switch. The resulting database backup
file contains the commands necessary to create the databases and users, making a
complete database restore a snap.

Ex:

$ mysqldump -u root -p --all-databases > my_backup.sql

To create an empty copy of your database—just the structure—for testing, use the

--no-data switch:

$ mysqldump -u root -p --no-data store > structure.sql

You can also do the opposite and just back up the data with the --no-create-info

switch:

$ mysqldump -u root -p --no-create-info store > data.sql


Restoring a MySQL backup

If you did a backup of your database using mysqldump --all-databases to a file


called

my_backup.sql, you could restore your database:

mysql -u root -p < my_backup.sql

If you did a selective backup of only one database, it’s a bit more complex. To

restore that type of backup file, use the -D command-line switch:

mysql -u root -p -D store < my_backup.sql

A common method of representing a list of data is in CSV (comma-separated


values) format. The mysqldump command supports this format. All you need to
do is specify the --no-create-info, --tab, and --fields-terminated-by arguments:

mysqldump -u root -p --no-create-info --tab=/home/jon --fields-terminated-


by=',' store

This tells mysqldump to generate separate files for each table in the store
database.

They’ll all be placed in the directory /home/jon. Each file’s name will be the
name of the table that is being exported. Each file contains the records in the
respective table separated by the comma character (,) that was specified on the
command line.

The mysqlimport command


To bring in data from another database or a spreadsheet in CSV format.
To import the data use the mysqlimport command:

mysqlimport -u root -p --fields-terminated-by=',' store books.txt

Save MySQL query results into a text or CSV file

Here is an easy way to write MySQL query results into a .txt or .CSV files
through the select statement.

Save query result into a .txt file :


mysql> SELECT rno, name FROM stud INTO OUTFILE 'e:/mb.txt';

101 aaa

102 bbb

Save query result into a mb.csv file :


mysql> SELECT rno,name FROM stud INTO OUTFILE 'e:/mb.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\
n';

Advanced SQL
Indexes
The data in an index is sorted and organized to make finding a specific value as quick as possible.
Because the values are sorted.

When indexes are used


If you do a simple SELECT statement without a WHERE clause, an index won’t
be used.
There are three major areas where an index can be used:
In a WHERE clause
For example, the query SELECT * FROM authors WHERE author = 'Ellen
Siever';would use an index on the author column if it’s available.
In an ORDER BY clause
For example, the query SELECT * FROM contacts ORDER BY author; would
use an index on the author column if it’s available.
In MIN and MAX clauses
For example, the query would use an index if the column that is specified in the
MIN or MAX function has an index.

UNIQUE INDEX in MySQL is used to ensure that the values in one or multiple
columns are unique across all rows (or records) in a table. It prevents any duplicate
entry into the table. It can be useful in situations where uniqueness has to be
ensured but it doesn't necessarily need to be a primary key.

In other words, when we create a UNIQUE INDEX on one or more columns in a table,
MySQL guarantees that the values in those columns will be unique for every row in the table.
The UNIQUE INDEX can be created at the time of table creation or it can be added later using
the ALTER TABLE statement. It can be declared on one or multiple columns, and it can also
include null values in the indexed columns.

As the uniqueness is enforced on one or more column(s) in a table, it is ensured that these
columns contain unique values only, but it can also be a NULL value though.

The use of UNIQUE INDEX in MySQL also improves efficiency by making data retrieval
faster, helps it retrieve the required data quickly concerning the search criteria that we mention
in the WHERE clause.

Differences between Unique Index and Primary Key

The focus of both PRIMARY KEY as well as UNIQUE INDEX in MySQL is to make sure
that a column must have a unique value in each of its rows.

But there are a few major differences between the two that should be highlighted. A
PRIMARY KEY is a special unique index that can be assigned to only one column/field of a
table. UNIQUE INDEX, on the other hand, isn't limited to having only one column in a table.
It can be applied to multiple columns. PRIMARY KEY doesn't allow the insertion of any null
value in a column. However, we can have null values in the case of a UNIQUE INDEX.
Previously, the allowance of null values was considered a bug, but that's not the case here.

When to Use Unique Index vs. Primary Key

As already mentioned, there can only be one primary key but multiple unique indexes within a
table.

A primary key prohibits the insertion of NULL values but a unique index doesn't.

Most importantly, a primary key is meant to enforce the referential integrity between the tables
and this makes sure that each of the columns in a table can be uniquely identified. Contrarily, a
unique index is used to ensure the uniqueness within a table.

https://www.scaler.com/topics/unique-index-in-mysql/

CREATE UNIQUE INDEX


1. The CREATE UNIQUE INDEX command creates a unique index on a table
(no duplicate values allowed)
2. Indexes are used to retrieve data from the database very fast. The users
cannot see the indexes, they are just used to speed up searches/queries.
3. The following SQL creates an index named "uidx_pid" on the "PersonID"
column in the "Persons" table:
CREATE UNIQUE INDEX authind ON authors (author);

Now use the following to DESCRIBE the table:


DESCRIBE authors;
which gives you this information:

Note: Updating a table with indexes takes more time than updating a table
without (because the indexes also need an update). So, only create indexes on
columns that will be frequently searched against.

Multicolumn indexes
It’s also possible to create MySQL indexes that use more than one column. A
multicolumn unique index ensures that the combination of column values is
unique.
The best columns to index are those that are likely to be used in the WHERE
clause, especially if you know that certain combinations of keys will be used.

Those are good columns to add to a multicolumn index. Order the columns in a
multicolumn index so that columns used frequently come first. MySQL uses a
multicolumn index to speed up a query even if only the first value of the index is
used.
Primary indexes are also unique. Only one primary index is allowed per table.
However, you can have as many unique indexes as your heart desires.

We’re going to do a query with a specific WHERE clause, and then use
EXPLAIN to get details about how it was processed by MySQL:
SELECT * FROM authors WHERE author = 'Arnold Robbins';
This returns the following:

+-----------+----------+----------------+
| author_id | title_id | author |
+-----------+----------+----------------+
| 3 | 2 | Arnold Robbins |
+-----------+----------+----------------+

The EXPLAIN keyword


Use the EXPLAIN keyword on a database that doesn’t have an index defined for
the authors table:
EXPLAIN SELECT * FROM authors WHERE author = 'Arnold Robbins';

EXPLAIN, in turn, gives you this output (which has wrapped a little):

+----+-------------+---------+------+---------------+------+---------+------+---

| id | select_type | table | type | possible_keys | key | key_len | ref |rows | Extra |


+----+-------------+---------+------+---------------+------+---------+------+---

| 1 | SIMPLE | authors | ALL | NULL | NULL | NULL | NULL |4 | Using where |


+----+-------------+---------+------+---------------+------+---------+------+---
1 row in set (0.00 sec)

The EXPLAIN output provides a wealth of information about how MySQL


processed the query.
It tells you:
• That you’re using the authors table.
• The query type is ALL, so every record is scanned to check for the correct
value.
• The possible_keys is NULL because no index matches.
• The key used by this query is currently NULL.
• The key_len is the key length; currently NULL, as no key was used.
• The ref column displays which columns or constants are used with the key;
currently NULL.
• The number of rows that must be searched through for this query.

After creating a unique index on authors called authind using the syntax from
Example , rerun the EXPLAIN query:
-+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+-------+---------------+---------+---------+------

| 1 | SIMPLE | authors | const | authind | authind | 126 | const| 1 | |


+----+-------------+---------+-------+---------------+---------+---------+------
1 row in set (0.12 sec)
Notice that many of the values have changed regarding the indexing:
• ref means that rows with matching index values are read from this table for
matches.
• possible_keys displays a possible key of authind.
• key displays that the authind key was used.
• key_len displays the length of the key as 126.
• ref tells you that a constant key is being used.
• rows show that one row was searched, which is much less than before.
The comparison shows that adding the index saves a lot of processing time, even
for this small table.

Selecting with the LEFT JOIN ON Clause


A left join simply allows you to query two tables that are linked together by a
relationship, but allows one of the tables to return rows even if there isn’t a
matching row in the other table.
Using the bookstore tables as an example, you might want to create a query that
returns users and their purchases, but also lists users who have yet to purchase
anything.

SELECT * FROM users LEFT JOIN purchases ON users.user_id =


purchases.user_id;

Selecting with GROUP BY


When selecting from the database, you can group rows of data together and
perform actions on the grouped data such as calculating an average or counting
the grouped rows.
The GROUP BY keyword specifies on which column or columns to group.
The following displays the number of authors per book:

SELECT title,COUNT(author_id) FROM books NATURAL JOIN authors


GROUP BY title;

Because the results are grouped by title, it’s possible to count the number of
authors for each title.

Common functions that can be used on columns that aren’t included


in the GROUP BY are

Using Database Functions

Functions we can use with MYSQL Queries are


 String Functions
 Date & Time Functions
String functions

Concatenation.
Just like the process of putting strings together with the PHP dot operator (.),
which is a period, MySQL can paste together strings fromdata fields with the
CONCAT function.
For example, if you want to return a single field that combines the title with
the number of pages, you could use CONCAT.

SELECT CONCAT(title,' has ',pages,' pages.') FROM books;

You might also like