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

Unit 5 PHP

This document provides an overview of MySQL, a web-based database system developed by Oracle Corporation, highlighting its features, advantages, and usage with PHP. It explains how to connect to MySQL using MySQLi and PDO, create databases and tables, and perform basic operations like inserting, updating, and deleting data. Additionally, it includes code examples for various operations in both MySQLi and PDO syntax.

Uploaded by

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

Unit 5 PHP

This document provides an overview of MySQL, a web-based database system developed by Oracle Corporation, highlighting its features, advantages, and usage with PHP. It explains how to connect to MySQL using MySQLi and PDO, create databases and tables, and perform basic operations like inserting, updating, and deleting data. Additionally, it includes code examples for various operations in both MySQLi and PDO syntax.

Uploaded by

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

Unit 5

PHP MySQL Database

What is MySQL?

 MySQL is a database system used on the web

 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

 MySQL uses standard SQL

 MySQL compiles on a number of platforms

 MySQL is free to download and use

 MySQL is developed, distributed, and supported by Oracle Corporation

PHP Connect to MySQL


PHP 5 and later can work with a MySQL database using:
 MySQLi extension (the "i" stands for improved)
 PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this
extension was deprecated in 2012.

When to Use MySQLi or PDO:


Both MySQLi and PDO have their advantages:
PDO will work on 12 different database systems, whereas MySQLi will only
work with MySQL databases.
So, if you have to switch your project to use another database, 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 Examples in Both MySQLi and PDO Syntax


There are three ways of working with PHP and MySQL:
 MySQLi (object-oriented)
 MySQLi (procedural)
 PDO

Open a Connection to MySQL

Example (MySQLi Object-Oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";

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

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);

// set the PDO error mode to exception


$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

Note: In the PDO example above we have also specified a database (myDB). PDO require a valid
database to connect to. If no database is specified, an exception is thrown.

Close the Connection


The connection will be closed automatically when the script ends. To close the connection before,
use the following:

MySQLi Object-Oriented:
$conn->close();

MySQLi Procedural:
mysqli_close($conn);

PDO:
$conn = null;

PHP Create a MySQL Database


Create a MySQL Database Using MySQLi and PDO
The CREATE DATABASE statement is used to create a database in MySQL.

The following examples create a database named "myDB":


Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

Note: When you create a new database, you must only specify the first three arguments to the
mysqli object (servername, username and password).

Tip: If you have to use a specific port, add an empty string for the database-name argument, like this:
new mysqli("localhost", "username", "password", "", port)

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

Create a MySQL Table Using MySQLi and PDO


The CREATE TABLE statement is used to create a table in MySQL.

We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname", "email"
and "reg_date":

CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

Notes on the table above:

The data type specifies what type of data the column can hold.

After the data type, you can specify other optional attributes for each column:

 NOT NULL - Each row must contain a value for that column, null values are not
allowed

 DEFAULT value - Set a default value that is added when no other value is passed

 UNSIGNED - Used for number types, limits the stored data to positive numbers and
zero

 AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each
time a new record is added

 PRIMARY KEY - Used to uniquely identify the rows in a table. The column with
PRIMARY KEY setting is often an ID number, and is often used with
AUTO_INCREMENT

Each table should have a primary key column (in this case: the "id" column). Its value must
be unique for each record in the table.

Example (MySQLi Object-oriented)


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

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

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


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

$conn->close();
?>

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

// use exec() because no results are returned


$conn->exec($sql);
echo "Table MyGuests created successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

Insert Data Into MySQL Using MySQLi and PDO


After a database and a table have been created, we can start adding data in them.

Here are some syntax rules to follow:

 The SQL query must be quoted in PHP

 String values inside the SQL query must be quoted

 Numeric values must not be quoted

 The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]')";

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


echo "New record created successfully";
}

else

{
echo "Error: " . $sql . "<br>" . $conn->error;
}
Example (PDO)

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";

Insert Multiple Records Into MySQL Using MySQLi and PDO


Multiple SQL statements must be executed with the mysqli_multi_query() function.

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";

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


echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

Update Data
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

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


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

Delete Data
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";

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


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

Select Data (Retrieve Data)


Example (MySQLi Object-oriented)
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
First, we set up an SQL query that selects the id, firstname and lastname
columns from the MyGuests table. The next line of code runs the query and
puts the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows
returned.

If there are more than zero rows returned, the function fetch_assoc() puts
all the results into an associative array that we can loop through.
The while() loop loops through the result set and outputs the data from the
id, firstname and lastname columns.

You can also put the result in an HTML table:


$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".
$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}

Select Data With PDO (+ Prepared Statements)


The following example uses prepared statements.
It selects the id, firstname and lastname columns from the MyGuests
table and displays it in an HTML table:
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator {


function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}

function current() {
return "<td style='width:150px;border:1px solid black;'>" .
parent::current(). "</td>";
}

function beginChildren() {
echo "<tr>";
}

function endChildren() {
echo "</tr>" . "\n";
}
}

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM
MyGuests");
$stmt->execute();

// set the resulting array to associative


$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt-
>fetchAll())) as $k=>$v) {
echo $v;
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

You might also like