0 ratings0% found this document useful (0 votes) 260 views17 pagesUnit V (Accessing MYSQL)
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
CHAPTER 10
ACCESSING MySQL AND USING PHP
WITH MySQL
Accessing MySQL —Using MySQL Client and Using PHP MyAdmin, MySQL Commands,
Using PHP with MySQL: PHP MySQL Functions, connecting to MySQL and Selecting the
Database, Executing Simple Queries, Retrieving Query Results, Counting Returned Records,
Updating Records with PHP,
ACCESSING MySQL:
In order to create tables, add records, and request information from a database, some sort of
client is necessary to communicate with the MySQL server.
Client applications focus on two: the mysql client and the Web-based phpMyAdmin. A third
option, the MySQL Query Browser (www.mysql.com).
If you are working on your own computer, see Appendix A, “Installation,” for instructions on
installing MySQL, starting MySQL, and creating MySQL users. If you are using a hosted server,
your Web host should provide you with the database access. Depending upon the hosting, you may
be provided with phpMyAdmin, but not be able to use the command-line MySQL client.
[tor USING THE MySQL CLIENT ihn
The MySQL client is normally installed with the rest of the MySQL software. Although the
mysql client does not have a pretty graphical interface, it’s a reliable, standard tool that's easy to
we and behaves consistently on many different operating systems,
The mysq] client is accessed from a command-line interface, be it the Terminal application in
Linux or Mac OS X or a DOS prompt in Windows. If you're not comfortable with command-line
interactions, you might find this interface to be challenging, but it becomes easy to use in no time.
To start the application from the command line, type its name and press Return or Enter:
MySQL
sag Pending upon the server (or your computer), you may need to enter the full path in order to
the application.For example: MP)
using MA!
/Applications/MAMP/Library/bin/m, oa
sql (Mac OS X-
OA Termina
window in
Mac OS .
-
ce i
noory Leer
ona nian [| console (although
San
=
affect how it runs. The
i i icatic can add arguments to Most
When invoking this application, you 3 Bs asine) URL aa
common arguments are the username, password,
address). You want to connect using.
‘You establish these arguments like so:
mysq] -u username -h hostname -p
Where,
> The -p option will cause the client to prompt you for the password.
© You can also specify the password on this line if you prefer by typing it directly afer,
the -p prompt but it will be visible, which is insecure.
> The -h hostname argument is optional
© you can leave it off unless you cannot connect to the MySQL server without it.
> Within the mysql client, every statement (SQL command) needs to be terminated by a
semicolon.
> These semicolons are an indication to the client that the query is complete and should be
run.
» The semicolons are not part of the SQL itself (this is a common point of confusion). What
this also means is that you can continue the same SQL statement over several lines withit
the mysq] client, which makes it easier to read and to edit, should that be necessary.
‘As a quick demonstration of accessing and using the mysql client, th all show
you how to start the mysql client, select a database to use, ea the client. aallowing these
se
eps
The MySQL server must be running
You must have a username an
mame and password w;
hy ith proper access.
¢ following steps and co ope
the fo “ontinue to provide dows
#e OS X. While the appearance sy Frovide images using the mysql client on both Win
Mo
ff 5 hort,
The concemed about Why one image ie the steps and results will be identical. So - a a
qt veal cent ‘ows the DOS prompt and the next a Terminal
ys
1, Access your system from & comman,
» On Unix systems and Mac og 4 : bic
a similar application S X, this is just a matter of bringing up the Termil
\d line interface.
Press Enter (or click OK) to bring up a DOS prompt.
— 9
ED RD ergs mer totes, document or tenet
TOMES. andl Window wail open Ror you
|) Seen cmd
@ Executing cmd within the Run prompt in Windows
‘one
way to access a DOS prompt interface,
Invoke the mysql client, using the appropriate command
/path/to/mysqV/bin/mysql -u + username -p
The /path/to/mysql part of this step will be largely dictated by the operating system you
are running and where MySQL was installed.
Already provided two options, based upon installations of MAMP on Mac OS X or
XAMPP on Windows (both are installed in Appendix A).
1 /Applications/MANP/Library/bin/ays4l —u rest —p
Enter password: Mt
@ Access the mysq| client by entering the full
path to the utility, along with the proper arguments.
The basic premise is that you are running the mysql client, connecting as username,
and requesting to be prompted for the password. Not to overstate the point, but the
aPHP & Mys
ie episod in M50
ablish
aust already be estab!
username and password values that you use ™
valid user
enter
3. Enter the password at the prompt and press Return/t
user yO
> The password you use here should be for oo bination
step. If you used the proper username/passw'
d access).
x specified in the prec
(ie., someone »,
correct values (see Appendix A fir
> — Ifaccess is denied, ou! polar not using the correct
IB C\Windows aystem i) Nome ene Seeeeveetentate 25
sor SO
icopet te che Myst monitor; Commands ond with
S°8 AysGL Community Server (GPL?
ait righto
wy tee
ecle is a registered trademark of Oracle Corporstteo,cceive
ei * Other nance nay be tradenarks of
eae Ke> 2098, 2018, Oracle and/or its affiliates
Type ‘help:’ or *\h’ for help. Type *e'
|
Je input statenent.
+ co clear the current input |
pyeai> E |
f
like this,
@ ityou are successfully able to log in, you'll see a welcome message Il
4. Select the database you want to use.
USE test;
> The USE command selects the database to be used for every subsequent command,
> The test database is one that MySQL installs by default.
> Assuming it exists on your server, all users should be able to access it.
mysql> USE test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
cacebasachisogee
mya Bh
@ After getting into the mysql client, run a USE command to choose the
database with which you want to work.
5. Quit out of mysql.
exit
> You can also use the command quit to leave the client.
> This step you enter in the mysql client-does not require a semicolon at the end.Go (_-—__
wysgh_and Using PUP with Mysoy 16h
Type either exit or
Give the mysql client, “4* '© terminate your MySQL session and
4 Quit the Terminal or DOS console session
ait
» The command exit will terminate the curent session
» On Windows, it wll also close the DOS prompt window.
we! matters
1, Ifyou know in advance which database you will want to use, you can simplify Pe
starting mysql with
/path/to/mysqUbin/mysql -u username
- databasename
To see what else you can do with the mysql client, type
/path/to/mysqUbin/mysql help
3, The mysql client on most systems allows you to use the up and down arrows to scroll
through previously entered commands. If you make a mistake in typing a query, you can
scroll up to find it, and then correct the error.
4, In the mysql client, you can also terminate SQL commands using \G instead of the
semicolon. For queries that return results, using \G displays those results as a vertical
list, as opposed to a horizontal table, which is sometimes easier to peruse.
5. If you are in a long statement and make a mistake, cancel the current operation by
typing ¢ and pressing Return or Enter. If mysql thinks a closing single or double
quotation mark is missing (as indicated by the '> and "> prompts), you'll need to enter
the appropriate quotation mark first.
102 USING PHP MyADMIN
PHPMyAdmin (www.phpmyadmin.net) is one of the best and most popular applications
‘tte in PHP. Its sole purpose is to provide an interface toa MySQL server. It's somewhat easier
‘ad more natural to use than the mysql client but requires a PHP installation and must be accessed
‘rough a Web browser.
Ifyou’re running MySQL on your own computer, you might find that using the mysql client
‘makes more sense, as installing and configuring phpMyAdmin constitutes unnecessary extra worki
(although all-in-one PHP and MySQL installers
Web host is virtually guaranteed to provide PhpM:
and the mysql client may not be an opti
U
To use PHPMyAdmin:
Note:
>
>
Pur
u), [fusing a hosted ser
yor
ay do this for om
xian as the primary way (0 ei
on '
rough the basics
un th
sing phpMyAdmin isn’t hard, but the next steps ™
ser.
1. Access phpMyAdmin through your Web browser:
The URL you use will depend upon your situation
his might be Mp2”
Jp host will provide y'
hough the site’s control pang
locathost/phpMyAdmin/.
If runni yor mputer, tl
ing on your own compl ou with the proper URL.
If running on a hosted site, your Wel
In all likelihood, phpMyAdmin would be available #
(should one exist).
© The fst phpMyAdmin page (when connected 8
Srutiple databases). ans
phpMyAdmin will only work if it’s been properly configured to connect to MySQL with
a valid username/ password/hostname combination.
‘You're probably not using the correct values (see Appendix A for instructions on creating
users).ypsigland Using PHP with MySQL
163
i
Welcome to phpMyAdmin
@ Every client application
requires a proper none
cori ves AGL a saat RO possword/mostname combi
See econo ee ert mtoract with te
MySOL server.
how to change the MySQL user that phpMyAdmin is connecting as?
That user might have aceess to one database, several databases, or every database.
On a hosted site where you have just one database, that database will probably
already be selected for you.
On your own computer, with phpMyAdmin connecting as the MySQL root user,
You would see a pull-down menu or a simple list of available databases.
3. Click on a table name in the left column to select that table.
from the left column
changes the options
‘on the right side of
the page.pur
form common task
os
he page) (0 PO
ight side of t :
a SELECT auery
4. Use the tabs and links (on the F J the Insert tab cr
For example, the Browse tab performs
for adding new records to enter SQL commands
dow
5. Use the SQL tab or the SQL query Win!
celal
—e-
nae oo comin pen pn
Komen precy Bow m
js epee ecm =
@ The SQL tab, in the
main part of the window,
can be used to run any |
SQL command.
populate, and manipulate tables. These mig
SQL commands that must be run to create,
look like
INSERT INTO tablename (coll,
col2) + VALUES (x, y)
@ The SQL window can also be
used to run commands. It pops
up after clicking the SQL icon
at the top of the left side of the
browser (see the second icon
from the left in (3).
These commands can be run using the mysq] client, dmin, other i
pod a , PhpMy Admin, or amy interface.
as run them within phpMyAdmin, just enter them into one of the SQL a and click
0.10.3 MySQL COMMANDS, USING PHP WITH MySOL }
MySQL commands in PHP
are used to interact with a MySQL database from a PHP seript
The emphasis is on two topics: how to define a database using MySQL's rules and data types.
ynd how to connect with the MySQL server
SQL, which stands for Structured Query Language, is a set of special words that are only a
toconnect with databases, SQL is a deceptively simple language to learn and use, but it is incredibly
powerful
Using PHP with MySQL involves executing MySQL commands within PHP code to interact
with a MySQL database.
[104 PHP MySQL FUNCTIONS: : —__—
PHP provides several functions for interacting with MySQL. databases. Enabling you to:
Create, read, update, and delete data (CRUD operations).
Execute various SQL queries to manage and manipulate data.
Types of Functions:
1. Legacy (mysql_*):
> Avoid using these in new projects due to security concerns and deprecation.
> Ifyou encounter them in older code, migrate to mysqli or PDO.
DO (PHP Data Objects):
> General-purpose database abstraction layer, supporting various database systems
(including MySQL).
> Provides consistent interface for working with different databases.
> Often preferred for new projects due to its flexibility and database-agnostic nature.
3. Modern (mysqli):
> — Object-oriented approach for enhianced security and performance.
> Supports prepared statements to prevent SQL injection attacks.
10.4.1 MySQL-related PHP Functions:
1. Database Connection Functions:
In PHP, you can use the PDO (PHP Data Objects) or MySQLi (MySQL Improved) extension
to connect to databases,
mysqli_connect(): Opens a new connection to the MySQL server.
mysqli_close(): Closes the connection to the MySQL server.166 —PHP & u,
Example: 7
<2php
Sconn = mysqli_connect(“localhost”, “username”, “password”, “dbname”);
Check connection
if ({Sconn) {
die(“Connection failed: ” . mysq)
}
// Perform database operations
mysqli_close(Sconn);
>
connect_error());
2. Query Execution Functions:
| In PHP, you can execute SQL queries using various functions provided by database extensions
like MySQLi and PDO.
mysqli_query(): Performs a query on the database.
mysqli_fetch_assoc(): Fetches a result row as an associative array.
mysqli_fetch_array(): Fetches a result row as an associative, numeric array, or both.
Example:
<2php
$result = mysqli_query(Sconn, “SELECT * FROM your_table”);
while (Srow = mysqli_fetch_assoc(Sresult)) {
// Process each row
3
>
3. Error Handling Functions:
In PHP, error handling can be done using various functions and techniques to manage and log
errors during script execution.
mysqli_error(): Returns a string description of the last error.
mysqli_errno(): Retuns the error code for the most recent MySQLi function call.
Example:
‘
Transaction Functions:
In PHP, transactions are used to group multiple database operations into a single, atomic unit.
‘Irnsactions ensure that either all the operations within the unit are executed successfully or none
of them are. p
mysqli_begin_transaction(): Initiates a transaction.
‘mysqli_commit(): Commits the current transaction.
mysqli_rollback(): Rolls back the current transaction.
Eumple:
‘
These are some essential MySQL funetions in PHP.
10.4.2 MySQL commands that are frequently w!
MySQL:
When working with PHP and MySQL, you often use a vari
operations on the database.
se me i
A we
establishing a connection between your PHP script and
sed when working with PHP ang
ty of SQL commands to perform
10.5 CONNECTING TO MySQL
Connecting to MySQL in PHP involves
a MySQL database server.
Using MySQLi (MySQL Improved):
1. Setting up Connection Parameters:
Sservername = “localhost”; // Replace with your MySQL server address
Susername = “your_username”; // Replace with your MySQL username
Spassword = “your_password”; // Replace with your MySQL password
Sdatabase = “your_database”; // Replace with your MySQL database name
2. Creating a Conneetior
Sconn = new mysqli($servername, $username, $password, $database);EP UP vein,
et h Mysoy
F “pecking Connection =
* j(¢6conn->connect &rror)
die(*Connection faiieg,
oun connect erry)
5
performing Operations,
Now, YOU CAN USe the Seonn
Closing Connection;
biect to execute SQL queries and perform database he
5 sconn->close();
a
6 SELECTING THE pay
Selecting @ database in pp involves estabtishin ay SQL
: Cstablishing a ion to a My ane
fying oe any ore Want 0 Work with, Ths oe a crucial bocanse it
ines Which database the Subsequent ‘queries will target
Setting up Connection Parameters:
Sservername = “locathoser,
$username =
“Your_username;
Spassword = “your Password”;
Sdatabase = “your_database™;
Creating a Connection:
Sconn = new mysqli(Sservernam,
Checking Connection:
if (Sconn->connect_error) {
die(“Connection failed: ”
}
| Selecting the Database:
Sconn->select_db(Sdatabase);
Afer this step, all the subsequent queries using Sconn will be executed on the specified
Gabase,
and
om,
fas
and
3 Sconn->connect_error);
5. Closing Connection:
Sconn->close();170
then sending SQL queri
to execute simple queries like SE
10.7 EXECUTING SIMPLE Q
UERIES
involves establis
ver, Below are ©
et TE, and DI
ntoaM,
amples using both MySQT
ELETE ;
hing a connection
Executing simple queries in PHP inv
1es to the database 8
ike 8 RECT, INSERT, UPDA
Setting up Connection Parameters:
Sservername = “localhost”;
Susername = “your_username”s
Spassword = “your_password”s
-your_database”;
Sdatabase
Creating 2 Connection: seword, Sdatabase);
Sconn = new mysqli(Sservername, Susernamer Spat
‘Checking Connection:
if (Sconn->connect_error) {
die(“Connection failed: ” - Sconn->connect_error);
}
Executing SELECT Query:
Sresult = Sconn>query(“SELECT column, column2 FROM my_table WHERE
condition”);
while (Srow = Sresult->fetch_assoc()) {
// Process each row
}
Executing INSERT Query:
Sconn->query(“INSERT INTO my_table (columnl, column2) VALUES (‘valuel’,
‘value2’)”);
Executing UPDATE Query:
$conn->query(“UPDATE my_table SET columml = ‘new_value’ WHERE condition”);
Executing DELETE Query:
Sconn->query(“DELETE FROM my_table WHERE condition”);
Closing Connection:
Sconn->close();7 OO —
and Using PHP sity
ysolan PUP with Mysoy
v7
5 ae
RETRIEVING QUERY RES) Ts - = ”q
executing SQL queries i PHP. :
whe a YOU need to re
\ scuting SELECT Query ‘Oretrieve the results returned by thowe queries
Fs
galt = SCON>qQuery(“SEL BE-y wil
n
aition”)s » column? FROM my table WHERE
ot
geiching Results:
p site (SOW = Sresultfetch_assoc() (
Process each row
echo Srow|‘columnt?} ,«, >, Srow|‘column2'}, «
,
ERE
To count the number of returned records after executing a SELECT query in PHP, you can use
lie COUNT) SQL function or count the rows in the result set.
1. Executing SELECT Query:
Sresult = Sconn->query(“SELECT COUNT(*) as count FROM my table WHERE
condition”);
Srow = Sresult->fetch_assoc();
Scount = $row[‘count’];
echo “Number of records: ”. Scount;
you don't want to use the COUNT( function, you can use the num_rows property of the
elt object:172 Fi
vine WHERE condition”);
Sresat = Scons->query(“SELECT * FROM™
Scount = Sresult--num_rowss
echo “Number of records: ”. Scounts E
}
10.10 UPDATING RECORDS WITH ‘ ing an UPD/
volves executing an UPDATE query
Updating records in a MySQL database using PHP in
1. Setting up Connection Parameters:
‘Sservername = “localhost”;
Susername = “your_username”;
Spassword = “your_password”s
Sdatabase = “your_database”;
2. Creating a Connection:
eoun = new myoqiSeervername, Seseraamn, Spassmordy SUMtADA2:)
3. Checking Connection:
if (Sconn->connect_error) { J
die(“Connection failed: ”. Sconn->connect_error)}
4. Updating Records:
Snew_value = “updated_value”;
Scondition = “your_condition”;
‘Ssql = “UPDATE my_table SET
Sresult = Sconn->query(Ssa);cing MPSOL and Using PHP with Myso1
“
— 173
ig.11 MODEL QUESTIONS kK” wa
gnswer the following questions, 2 coin
1. How to access MySQL?
2. What are the query execution function?
3. What are functions used in database connection?
4. What are the functions used in transaction?
5. What are an error handling functions?
6 or 8 marks
answer the following questions.
i.
Zz
3:
4.
5,
Explain about how to use the MySQL client.
Describe how to use phpMyAdmin.
Briefly explain about the PHP MySQL function.
Explain how to establish a connecting to MySQL?
Briefly explain about how to run a simple query with example.
kk kkk