PHP Mysql: Prof. N.Nalini Scope VIT

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

PHP MySQL

Prof. N.Nalini
SCOPE
VIT
PHP and MySQL
• Three ways of working with PHP and
MySQL:
– MySQLi (object-oriented)
– MySQLi (procedural)
– PDO
MySQLi VS PDO
• PDO will work on 12 different database systems, whereas MySQLi
will only work with MySQL databases.
• PDO makes the process easy. You only have to change the
connection string and a few queries. With MySQLi, you will need to
rewrite the entire code - queries included.
• Both are object-oriented, but MySQLi also offers a procedural API.
• Both support Prepared Statements. Prepared Statements protect
from SQL injection, and are very important for web application
security.
MYSQL
• MySQL is the most popular open-source
database system.
• The data in MySQL is stored in database
objects called tables.
• A table is a collections of related data
entries and it consists of columns and
rows.
• Databases are useful when storing
information categorically.
Database Tables
• A database most often contains one or
more tables. Tables contain records (rows)
with data.
• Below is an example of a table called
"Persons":
Data Types (TEXT)
• CHAR(size) – fixed length string. Contains
letters, numbers, special char.
• VARCHAR – variable length string.
Contains letters, numbers, special char.
• TEXT – holds string with max length
• LONGTEXT
• MEDIUMTEXT
• BLOB – binary large objects.
• LONGBLOB
• MEDIUMBLOB
Number Types
• INT(size)
• FLOAT(size,d)
• DOUBLE (size,d)
• DECIMAL (size,d)
Date Types
• DATE() - YYYY-MM-DD
• DATETIME() - YYYY-MM-DD HH:MM:SS
• TIME() - HH:MM:SS
• YEAR() - A year in two-digit or four-digit format
• TIMESTAMP() - TIMESTAMP values are stored
as the number of seconds since the Unix epoch
('1970-01-01 00:00:00' UTC).
Creating mysql database
• Display available databases
– Show databases;
• Create database
– Create database <dbname>;
• Giving permission to database
– Use <dbname>
• Creating table
– Create table <tablename>();
• Show list of tables
– Show tables;
• SQL can be divided
– The Data Manipulation Language (DML)
– The Data Definition Language (DDL).
– Data Control Language (DCL):  Grant  Revoke
DML
• INSERT INTO - inserts new data into a database
• SELECT - extracts data from a database
• *
• Where
• And |or
• UPDATE - updates data in a database
• Set
• where
• DELETE - deletes data from a database
• from
DDL
• CREATE DATABASE - creates a new
database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
Queries
• A query is a question or a request.
• With MySQL, we can query a database for
specific information and have a recordset
returned.
• Look at the following query:
• SELECT LastName FROM Persons
MySQL Functions
MySQL functions allows you to access
MySQL database servers.
• mysqli_connect – connect to DB
• mysqli_select_db – select DB
• mysqli_query – executes query
• mysqli_error – returns error desc of last
mysql operation.
• mysqli_close – close the connection with
DB.
MySQL Functions
• mysqli_fetch_array – returns a row from recordset as
assoc array and/or numeric array
• mysqli_fetch_assoc – returns a row from recordset as
assoc array
• mysqli_fetch_row – returns a row from recordset as
numeric array.
• mysqli_affected_rows() – returns the no. of affected
rows(update)
• mysqli_num_fields – returns no of fields in record set
• mysqli_num_rows returns no of rows in record set
MySQL Functions
• get_resource_type () - gets the type of the given resource(not
mysql function)
• mysqli_get_client_info() returns a string that represents the client
library version.
• mysqli_get_server_info() - Retrieves the MySQL server version.
• mysqli_pconnect() — Open a persistent connection to a MySQL
server
• mysqli_free_result() — Free result memory
• mysqli_list_dbs() — Lists all databases.
MySQL - Connect
Create Connection:
Before can access data in a database, must create a
connection to the database. In PHP, this is done with
the mysqli_connect() function.

mysqli_connect(servername,username,password);

E.g: <?php
$con = mysqli_connect("localhost",“root","admin“,”sample”);
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
?>

21
My SQL - Close

Close Connection:
The connection will be closed automatically when the script ends. To close
the connection before, use the mysqli_close() function:

mysqli_close($con);

<?php
E.g: $con = mysqli_connect("localhost",“root","admin“,”sample”);
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
//some code
mysqli_close($con);
?>

22
My SQL – Query
All DDL & DML queries can be executed by this function.

mysqli_query($query, $con);
E.g: Create DB

<?php
include(“connect.php”);
if (mysqli_query(" CREATE DATABASE sample if not exists",$con))
echo "Database created";
else
echo "Error creating database: " . mysqli_error();
mysqli_close($con);
?>

23
My SQL – Select DB

Database selection can be done by this function.

mysqli_select_db($dbname, $con);
E.g:

<?php
include(“connect.php”);
echo "Connection to the server was successful!<br/>";
echo "Database was selected!<br/>";
?>

24
My SQL – Query
E.g: select from table

<?php
include(“connect.php”);
$query = “select * from mytable”;
$selected_recs = mysqli_query($query, $con))
mysqli_close($con);
?>

25
<?php
include(“connect.php”);

$query ="Select * from employee";

$ result =mysqli_query($query,$connection)
or die("query failed:".mysqli_error());

While($row = mysqli_fetch_array($result))
{
echo $row[‘cn1’],$row[cn2];
}
?>
My SQL – Query

E.g: Drop DB

<?php
include(“connect.php”);
if (mysqli_query(“DROP DATABASE “.$dbname,$con))
echo "Database dropped";
else
echo "Error in dropping database: " . mysqli_error();
mysqli_close($con);
?>

27
My SQL – Query
E.g: create Table

<?php
include(“connect.php”);
$query = “create table mytable ( id int(3), name varchar(20), desc1 varchar(20),
primary key(id))”;
If ( mysqli_query($query, $con))
echo “mytable was created”;
Else
echo “error “.mysqli_error();
mysqli_close($con);
?>

28
My SQL – Query

E.g: Alter Table

<?php
include(“connect.php”);
$query =“alter table mytable (add column age int(2), drop column desc1,
modify column name varchar(30))”;
if (mysqli_query($query,,$con))
echo “Table altered";
else
echo "Error in alteration: " . mysqli_error();
mysqli_close($con);
?>

29
My SQL – Query

E.g: Drop table

<?php
include(“connect.php”);
$query = “drop table mytable”;
If ( mysqli_query($query, $con))
echo “table dropped”;
Else
echo “error “.mysqli_error();
mysqli_close($con);
?>

30
My SQL – Query

E.g: Insert record

<?php
include(“connect.php”);
$pid = $_POST[‘fid’];
$pname = $_POST[‘fname’];
$query = “insert into mytable values($pid,’$pname’)”;
If ( mysqli_query($query, $con))
echo “record inserted”;
Else
echo “error “.mysqli_error();
mysqli_close($con);
?>

31
My SQL – Query

E.g: Delete record

<?php
include(“connect.php”);
$pid = $_POST[‘fid’];
$query = “delete from mytable where id = $pid”;
If ( mysqli_query($query, $con))
echo “record deleted”;
Else
echo “error “.mysqli_error();
mysqli_close($con);
?>

32
My SQL – Query
E.g: update table

<?php
include(“connect.php”);
$query = “update table mytable set id = 11 where name = \”John\” ”;
If ( mysqli_query($query, $con))
echo “record updated”;
Else
echo “error “. mysqli_error();
mysqli_close($con);
?>

33
My SQL – num_rows
mysqli_num_rows() – Retrieves the number of rows from a result set.
This command is only valid for statements like SELECT or SHOW that
return an actual result set.
E.g:

<?php
include(“connect.php”);
$result = mysqli_query("SELECT * FROM mytable", $link);
$num_rows = mysqli_num_rows($con);
echo "$num_rows Rows were selected";
?>

34
My SQL – num_fields
mysqli_num_fields() – Retrieves the number of fields from a result set.

E.g:

<?php
include(“connect.php”);
$result = mysqli_query($con,"SELECT * FROM mytable", $link);
$num_fields = mysqli_num_fields($con);
echo "$num_fields Fields were selected";
?>

35
My SQL – affected_rows
mysqli_affected_rows() – The number of rows in a result set on
success or FALSE on failure. It is valid for insert, delete, and update
commands only.
mysqli_affected_rows($recordset);
E.g:

<?php
include(“connect.php”);
$query = “update table mytable set id = 11 where name = \”John\” ”;
$result = mysqli_query($query,$con);
$num_rows = mysqli_affected_rows($result);
echo "$num_rows Rows were selected";
mysqli_close($con);
?>

36
My SQL – fetch_row

mysqli_fetch_row () - returns a numerical array that corresponds to the


fetched row. Returns FALSE if there are no more rows.
mysqli_fetch_row($recordset);
E.g:
<?php
include(“connect.php”);
$result = mysqli_query("SELECT * from mytable",$con);
while ($r1 =mysqli_fetch_row($result))
echo $r1[0], $r1[1]; // table has 2 fields only
mysqli_close($con);
?>

37
My SQL – fetch_array
Extended version of mysqli_fetch_row. Returns an
numeric/associative array that corresponds to the fetched row and moves
the internal data pointer ahead or FALSE if there are no more rows.
mysqli_fetch_array($recordset);

E.g:
<?php
include(“connect.php”);
$result = mysqli_query("SELECT * from student",$con);
while ($row=mysqli_fetch_array($result))
print_r($row); // prints rec as numeric & associative array
mysqli_close($con);
?>

38
My SQL – fetch_assoc
Returns an associative array that corresponds to the fetched row and
moves the internal data pointer ahead or FALSE if there are no more
rows. Here, field names are array keys .
mysqli_fetch_assoc($recordset);

E.g:
<?php
include(“connect.php”);
$result = mysqli_query("SELECT * from student",$con);
while ($row=mysqli_fetch_assoc($result))
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>"; // prints rec as associative array
mysqli_close($con);
?>

39
My SQL – fetch_field
Returns an object containing field information. This function can be used
to obtain information about fields in the provided query result.
msql_fetch_field($recordset);
The properties of the object are:
name - column name
table - name of the table the column belongs to
max_length - maximum length of the column
not_null - 1 if the column cannot be NULL
primary_key - 1 if the column is a primary key
unique_key - 1 if the column is a unique key
multiple_key - 1 if the column is a non-unique key
numeric - 1 if the column is numeric
blob - 1 if the column is a BLOB
type - the type of the column
unsigned - 1 if the column is unsigned
zerofill - 1 if the column is zero-filled

40
E.g: <?php
$con = mysqli_connect("localhost", "root", “admin") or
die(mysqli_error());
$db_selected = mysqli_select_db("suresh",$con);
$result = mysqli_query("SELECT * from emp",$con);
while ($property = mysqli_fetch_field($result))
{ echo "Field name: " . $property->name . "<br />";
echo "Table name: " . $property->table . "<br />";
echo "Default value: " . $property->def . "<br />";
echo "Max length: " . $property->max_length . "<br />";
echo "Not NULL: " . $property->not_null . "<br />";
echo "Primary Key: " . $property->primary_key . "<br />";
echo "Unique Key: " . $property->unique_key . "<br />";
echo "Mutliple Key: " . $property->multiple_key . "<br />";
echo "Numeric Field: " . $property->numeric . "<br />";
echo "BLOB: " . $property->blob . "<br />";
echo "Field Type: " . $property->type . "<br />";
echo "Unsigned: " . $property->unsigned . "<br />";
echo "Zero-filled: " . $property->zerofill . "<br /><br />";
}?>

41
Prepared Statements
• A prepared statement is a feature used to execute the same (or
similar) SQL statements repeatedly with high efficiency.
• Prepared statements basically work like this:
1. Prepare: An SQL statement template is created and sent to the
database. Certain values are left unspecified, called parameters
(labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
2. The database parses, compiles, and performs query optimization on
the SQL statement template, and stores the result without executing
it
3. Execute: At a later time, the application binds the values to the
parameters, and the database executes the statement. The
application may execute the statement as many times as it wants
with different values
Advantages of Prepared
Statement
• Prepared statements reduce parsing time as the preparation on the
query is done only once (although the statement is executed
multiple times)
• Bound parameters minimize bandwidth to the server as you need
send only the parameters each time, and not the whole query
• Prepared statements are very useful against SQL injections,
because parameter values, which are transmitted later using a
different protocol, need not be correctly escaped. If the original
statement template is not derived from external input, SQL injection
cannot occur.
PDO - PHP Data Object
• A set of PHP extensions that provide a core PDO class
and database specific drivers.
• Provides a vendor-neutral lightweight data-access
abstraction layer.
• Focus on data access abstraction rather than database
abstraction.
• PDO requires the new object oriented features in the
core of PHP 5, therefore it will not run with earlier
versions of PHP.
PDO - PHP Data Object
• The PHP Data Objects (PDO) extension defines a
lightweight, consistent interface for accessing databases
in PHP.
• Each database driver that implements the PDO interface
can expose database-specific features as regular
extension functions.
• Note:
– Cannot perform any database functions using the PDO
extension by itself
– Must use a database-specific PDO driver to access a database
server.
<?php
try {
$dbhost = 'localhost';
$dbname='hr';
$dbuser = 'root';
$dbpass = '';
$connec = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}catch (PDOException $e) {
echo "Error : " . $e->getMessage() . "<br/>";
die();
}
$sql = 'SELECT fname, lname, country FROM user_details ORDER BY country';
foreach ($connec->query($sql) as $row)
{
print $row['fname'] . " ";
print $row['lname'] . "-->";
print $row['country'] . "<br>";
}

You might also like