Accessing MySQL Database Using PHP and PDO

C
G
S
 
3
0
6
6
:
 
W
e
b
 
P
r
o
g
r
a
m
m
i
n
g
 
a
n
d
 
D
e
s
i
g
n
F
a
l
l
 
2
0
1
9
Accessing MySQL through PHP
Accessing Database
MySQL can be accessed from PHP in three ways:
Legacy non-OO mysql_ routines (deprecated)
New mysqli
Procedural version – similar to mysql_
OO version – similar to PDO
PDO - Portable Data Objects
We will use PDO for our examples.
https://www.php.net/manual/en/mysqlinfo.api.choosing.php
Accessing MySQL
https://www.php.net/manual/en/mysqlinfo.api.choosing.php
PDO: Connecting to MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database_name";
try {
 
$conn = new PDO("mysql:host=$servername;dbname=$database", $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();
}
// Do your work
// Then close the connection
$conn = null;
?>
Select Data
<?php
require_once "dbconnect.php";
$query = "SELECT employee_id, first_name, last_name, email FROM employees";
$stmt = $conn->query($query);
echo "<pre>\n";
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
    print_r($row);
}
echo "<pre>\n";
// Close the connection
$conn->close();
?>
p
do1.php
Select Data
<?php
require_once "dbconnect.php";
$query = "SELECT employee_id, first_name, last_name, email FROM employees";
$stmt = $conn->query($query);
echo "<table border='1'>";
echo "<tr>";
echo "<th>Employee ID</th>";
echo "<th>First Name</th>";
echo "<th>Last Name</th>";
echo "<th>Email Address</th>";
echo "</tr>";
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
    echo "<tr>";
    echo "<td>" . $row["employee_id"] . "</td>";
    echo "<td>" . $row["first_name"] . "</td>";
    echo "<td>" . $row["last_name"] . "</td>";
    echo "<td>" . $row["email"] . "</td>";
    echo "</tr>";
}
echo "</table>";
$conn->close();
?>
p
do2.php
Insert Data
<?php
require_once "dbconnect.php";
if(isset($_POST["submit"])){
 
$first_name = $_POST["first_name"];
 
$last_name = $_POST["last_name"];
 
$email = $_POST["email"];
 
$password = $_POST["password"];
 
$query = "INSERT INTO employees (first_name, last_name, email, password)  VALUES ('$first_name', '$last_name', '$email', '$password')";
 
echo("<pre>\n".$query."\n</pre>\n");
 
try{
  
$conn->exec($query);
  
echo "Employee added successfully.";
  
$conn = null;
 
}
 
catch(PDOException $e)
 
{
  
echo $query . "<br>" . $e->getMessage();
 
}
}
?>
pdo3_insert.php
Insert Data
<!DOCTYPE html>
<html>
<head>
 
<title>Add new employee</title>
</head>
<body>
 
<div>Add a new employee</div>
 
<form action="" method="post">
  
<p>First Name:<input type="text" name="first_name" autocomplete="off"></p>
  
<p>Last Name:<input type="text" name="last_name" autocomplete="off"></p>
  
<p>Email:<input type="text" name="email" autocomplete="off"></p>
  
<p>Password:<input type="password" name="password" autocomplete="off"></p>
  
<p><input type="submit" name="submit" value="Add"/></p>
 
</form>
</body>
</html>
pdo3_insert.php
Insert and Display List in Same Page
<?php
require_once "dbconnect.php";
if(isset($_POST["submit"])){
 
$first_name = $_POST["first_name"];
 
$last_name = $_POST["last_name"];
 
$email = $_POST["email"];
 
$password = $_POST["password"];
 
$query = "INSERT INTO employees (first_name, last_name, email, password) VALUES ('$first_name', '$last_name', '$email',
'$password')";
 
echo("<pre>\n".$query."\n</pre>\n");
 
try{
  
$conn->exec($query);
  
echo "Employee added successfully.";
 
}
 
catch(PDOException $e)
 
{
  
echo $query . "<br>" . $e->getMessage();
 
}
}
?>
pdo4.php
Insert and Display List in Same Page
<!DOCTYPE html>
<html>
<head>
 
<title>Add new employee</title>
</head>
<body>
 
<div>Add a new employee</div>
 
<form action="" method="post">
  
<p>First Name:<input type="text" name="first_name" autocomplete="off"></p>
  
<p>Last Name:<input type="text" name="last_name" autocomplete="off"></p>
  
<p>Email:<input type="text" name="email" autocomplete="off"></p>
  
<p>Password:<input type="password" name="password" autocomplete="off"></p>
  
<p><input type="submit" name="submit" value="Add"/></p>
 
</form>
</body>
</html>
pdo4.php
Insert and Display List in Same Page
<?php
$query = "SELECT employee_id, first_name, last_name, email FROM employees";
$stmt = $conn->query($query);
echo "<table border='1'>";
echo "<tr>";
echo "<th>Employee ID</th>";
echo "<th>First Name</th>";
echo "<th>Last Name</th>";
echo "<th>Email Address</th>";
echo "</tr>";
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
    echo "<tr>";
    echo "<td>" . $row["employee_id"] . "</td>";
    echo "<td>" . $row["first_name"] . "</td>";
    echo "<td>" . $row["last_name"] . "</td>";
    echo "<td>" . $row["email"] . "</td>";
    echo "</tr>";
}
echo "</table>";
$conn = null;
?>
pdo4.php
Delete Data
<?php
require_once "dbconnect.php";
if(isset($_POST["submit"])){
 
$employee_id = $_POST["employee_id"];
 
$query = "DELETE FROM employees WHERE employee_id =
$employee_id";
 
echo("<pre>\n".$query."\n</pre>\n");
 
 
try{
  
$conn->exec($query);
  
echo "Employee deleted successfully.";
  
$conn = null;
 
}
 
catch(PDOException $e)
 
{
  
echo $query . "<br>" . $e->getMessage();
 
}
}
?>
pdo5_delete.php
<!DOCTYPE html>
<html>
<head>
 
<title>Delete an Employee</title>
</head>
<body>
 
<p>Delete an employee</p>
 
<form method="post"><p>ID to Delete:
  
<input type="text" name="employee_id"></p>
  
<p><input type="submit" name="submit"
value="Delete"/></p>
 
</form>
</body>
</html>
Add/Delete in Same Page
<?php
require_once "dbconnect.php";
if(isset($_POST["submit"])){
 
$first_name = $_POST["first_name"];
 
$last_name = $_POST["last_name"];
 
$email = $_POST["email"];
 
$password = $_POST["password"];
 
$query = "INSERT INTO employees (first_name, last_name, email, password)  VALUES ('$first_name', '$last_name', '$email', '$password')";
 
 
try{
  
$conn->exec($query);
  
echo "Employee added successfully.";
 
}
 
catch(PDOException $e)
 
{
  
echo $query . "<br>" . $e->getMessage();
 
}
}
pdo6_del_list.php
Add/Delete in Same Page
if(isset($_POST["delete"])){
 
$employee_id = $_POST["employee_id"];
 
$query = "DELETE FROM employees WHERE employee_id = $employee_id";
 
try{
  
$conn->exec($query);
  
echo "Employee deleted successfully.";
 
}
 
catch(PDOException $e)
 
{
  
echo $query . "<br>" . $e->getMessage();
 
}
}
?>
pdo6_del_list.php
Add/Delete in Same Page
<!DOCTYPE html>
<html>
<head>
 
<title>Add new employee</title>
</head>
<body>
 
<div>Add a new employee</div>
 
<form action="" method="post">
  
<p>First Name:<input type="text" name="first_name" autocomplete="off"></p>
  
<p>Last Name:<input type="text" name="last_name" autocomplete="off"></p>
  
<p>Email:<input type="text" name="email" autocomplete="off"></p>
  
<p>Password:<input type="password" name="password" autocomplete="off"></p>
  
<p><input type="submit" name="submit" value="Add"/></p>
 
</form>
</body>
</html>
pdo6_del_list.php
Add/Delete in Same Page
<?php
$query = "SELECT employee_id, first_name, last_name, email FROM employees";
$stmt = $conn->query($query);
echo "<table border='1'>";
echo "<tr>";
echo "<th>Employee ID</th>";
echo "<th>First Name</th>";
echo "<th>Last Name</th>";
echo "<th>Email Address</th>";
echo "<th>Action</th>";
echo "</tr>";
echo "</table>";
$conn = null;
?>
pdo6_del_list.php
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
 
echo "<tr>";
 
echo "<td>" . $row["employee_id"] . "</td>";
 
echo "<td>" . $row["first_name"] . "</td>";
 
echo "<td>" . $row["last_name"] . "</td>";
 
echo "<td>" . $row["email"] . "</td>";
 
echo "<td><form method='POST'>\n";
 
echo "<input type='hidden' name='employee_id' value='". $row["employee_id"] . "'>\n";
 
echo "<input type='submit' name='delete' value='Delete'>\n";
 
echo "</td></form>";
 
echo "</tr>";
}
SQL Injection
SQL injection is a code injection technique, used to attack
data-driven applications, in which malicious SQL statements
are inserted into an entry field for execution (e.g. to dump the
database contents to the attacker). SQL injection must exploit
a security vulnerability in an application's software, for
example, when user input is either incorrectly filtered for
string literal escape characters embedded in SQL statements
or user input is not strongly typed and unexpectedly executed.
SQL injection is mostly known as an attack vector for websites
but can be used to attack any type of SQL database.
(Wikipedia)
<?php
require_once "dbconnect.php";
if(isset($_POST["submit"])){
 
$email = $_POST["email"];
 
$password = $_POST["password"];
 
$query = "SELECT * FROM employees WHERE email = '$email' AND
password = '$password'";
 
try{
  
$stmt = $conn->query($query);
  
$row = $stmt->fetch(PDO::FETCH_ASSOC);
  
print_r($row);
  
if($row === false){
   
echo "<p>Login incorrect.</p>";
  
} else{
   
echo "<p>Login success.</p>";
  
}
 
}
 
catch(PDOException $e)
 
{
  
echo $query . "<br>" . $e->getMessage();
 
}
}
?>
<!DOCTYPE html>
<html>
<head>
 
<title>Login</title>
</head>
<body>
 
<h4>Please Login</h4>
 
<form action="" method="post">
  
  
<p>Email:<input type="text"
name="email" autocomplete="off"></p>
  
<p>Password:<input type="password"
name="password" autocomplete="off"></p>
  
<p><input type="submit"
name="submit" value="Login"/></p>
 
</form>
</body>
</html>
login1.php
login1.php
login1.php
Remedy – Use Prepared Statements
……
$query = "SELECT * FROM employees WHERE 
email = 
:email 
AND password =
 
:password
";
 
 
…………..
 
try{
  
$stmt = $conn->prepare($query);
  
$stmt->bindParam(':email', $email);
  
$stmt->bindParam(':password', $password);
  
$stmt->execute();
  
$row = $stmt->fetch(PDO::FETCH_ASSOC);
  
print_r($row);
………….
When the statement is executed, the 
placeholders
 get replaced
with the 
actual strings 
and everything is automatically escaped!
login2.php
Self Study
Implement the Employee Edit page with PDO prepared
statement
Acknowledgement
Some content is used (directly or with some modification) from the
following sources:
- Charles Severance, University of Michigan School of Information
Slide Note
Embed
Share

Learn how to access a MySQL database using PHP through PDO (Portable Data Objects) with step-by-step examples for connecting to MySQL, selecting and displaying data in a web application. PDO provides a flexible and secure way to interact with databases in PHP programming.

  • PHP
  • MySQL
  • Database
  • Web Development
  • PDO

Uploaded on Oct 03, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. CGS 3066: Web Programming and Design CGS 3066: Web Programming and Design Fall 2019 Fall 2019 Accessing MySQL through PHP

  2. Accessing Database MySQL can be accessed from PHP in three ways: Legacy non-OO mysql_ routines (deprecated) New mysqli Procedural version similar to mysql_ OO version similar to PDO PDO - Portable Data Objects We will use PDO for our examples. https://www.php.net/manual/en/mysqlinfo.api.choosing.php

  3. Accessing MySQL https://www.php.net/manual/en/mysqlinfo.api.choosing.php

  4. PDO: Connecting to MySQL <?php $servername = "localhost"; $username = "username"; $password = "password"; $database = "database_name"; try { $conn = new PDO("mysql:host=$servername;dbname=$database", $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(); } // Do your work // Then close the connection $conn = null; ?>

  5. Select Data <?php pdo1.php require_once "dbconnect.php"; $query = "SELECT employee_id, first_name, last_name, email FROM employees"; $stmt = $conn->query($query); echo "<pre>\n"; while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { print_r($row); } echo "<pre>\n"; // Close the connection $conn->close(); ?>

  6. Select Data <?php pdo2.php require_once "dbconnect.php"; $query = "SELECT employee_id, first_name, last_name, email FROM employees"; $stmt = $conn->query($query); echo "<table border='1'>"; echo "<tr>"; echo "<th>Employee ID</th>"; echo "<th>First Name</th>"; echo "<th>Last Name</th>"; echo "<th>Email Address</th>"; echo "</tr>"; while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo "<tr>"; echo "<td>" . $row["employee_id"] . "</td>"; echo "<td>" . $row["first_name"] . "</td>"; echo "<td>" . $row["last_name"] . "</td>"; echo "<td>" . $row["email"] . "</td>"; echo "</tr>"; } echo "</table>"; $conn->close(); ?>

  7. Insert Data <?php pdo3_insert.php require_once "dbconnect.php"; if(isset($_POST["submit"])){ $first_name = $_POST["first_name"]; $last_name = $_POST["last_name"]; $email = $_POST["email"]; $password = $_POST["password"]; $query = "INSERT INTO employees (first_name, last_name, email, password) VALUES ('$first_name', '$last_name', '$email', '$password')"; echo("<pre>\n".$query."\n</pre>\n"); try{ $conn->exec($query); echo "Employee added successfully."; $conn = null; } catch(PDOException $e) { echo $query . "<br>" . $e->getMessage(); } } ?>

  8. Insert Data <!DOCTYPE html> pdo3_insert.php <html> <head> <title>Add new employee</title> </head> <body> <div>Add a new employee</div> <form action="" method="post"> <p>First Name:<input type="text" name="first_name" autocomplete="off"></p> <p>Last Name:<input type="text" name="last_name" autocomplete="off"></p> <p>Email:<input type="text" name="email" autocomplete="off"></p> <p>Password:<input type="password" name="password" autocomplete="off"></p> <p><input type="submit" name="submit" value="Add"/></p> </form> </body> </html>

  9. Insert and Display List in Same Page pdo4.php <?php require_once "dbconnect.php"; if(isset($_POST["submit"])){ $first_name = $_POST["first_name"]; $last_name = $_POST["last_name"]; $email = $_POST["email"]; $password = $_POST["password"]; '$password')"; $query = "INSERT INTO employees (first_name, last_name, email, password) VALUES ('$first_name', '$last_name', '$email', echo("<pre>\n".$query."\n</pre>\n"); try{ $conn->exec($query); echo "Employee added successfully."; } catch(PDOException $e) { echo $query . "<br>" . $e->getMessage(); } } ?>

  10. Insert and Display List in Same Page pdo4.php <!DOCTYPE html> <html> <head> <title>Add new employee</title> </head> <body> <div>Add a new employee</div> <form action="" method="post"> <p>First Name:<input type="text" name="first_name" autocomplete="off"></p> <p>Last Name:<input type="text" name="last_name" autocomplete="off"></p> <p>Email:<input type="text" name="email" autocomplete="off"></p> <p>Password:<input type="password" name="password" autocomplete="off"></p> <p><input type="submit" name="submit" value="Add"/></p> </form> </body> </html>

  11. Insert and Display List in Same Page pdo4.php <?php $query = "SELECT employee_id, first_name, last_name, email FROM employees"; $stmt = $conn->query($query); echo "<table border='1'>"; echo "<tr>"; echo "<th>Employee ID</th>"; echo "<th>First Name</th>"; echo "<th>Last Name</th>"; echo "<th>Email Address</th>"; echo "</tr>"; while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo "<tr>"; echo "<td>" . $row["employee_id"] . "</td>"; echo "<td>" . $row["first_name"] . "</td>"; echo "<td>" . $row["last_name"] . "</td>"; echo "<td>" . $row["email"] . "</td>"; echo "</tr>"; } echo "</table>"; $conn = null; ?>

  12. Delete Data pdo5_delete.php <!DOCTYPE html> <?php require_once "dbconnect.php"; <html> if(isset($_POST["submit"])){ <head> $employee_id = $_POST["employee_id"]; <title>Delete an Employee</title> $employee_id"; $query = "DELETE FROM employees WHERE employee_id = </head> echo("<pre>\n".$query."\n</pre>\n"); <body> <p>Delete an employee</p> try{ <form method="post"><p>ID to Delete: $conn->exec($query); <input type="text" name="employee_id"></p> echo "Employee deleted successfully."; value="Delete"/></p> <p><input type="submit" name="submit" $conn = null; </form> } catch(PDOException $e) </body> { </html> echo $query . "<br>" . $e->getMessage(); } } ?>

  13. Add/Delete in Same Page pdo6_del_list.php <?php require_once "dbconnect.php"; if(isset($_POST["submit"])){ $first_name = $_POST["first_name"]; $last_name = $_POST["last_name"]; $email = $_POST["email"]; $password = $_POST["password"]; $query = "INSERT INTO employees (first_name, last_name, email, password) VALUES ('$first_name', '$last_name', '$email', '$password')"; try{ $conn->exec($query); echo "Employee added successfully."; } catch(PDOException $e) { echo $query . "<br>" . $e->getMessage(); } }

  14. Add/Delete in Same Page pdo6_del_list.php if(isset($_POST["delete"])){ $employee_id = $_POST["employee_id"]; $query = "DELETE FROM employees WHERE employee_id = $employee_id"; try{ $conn->exec($query); echo "Employee deleted successfully."; } catch(PDOException $e) { echo $query . "<br>" . $e->getMessage(); } } ?>

  15. Add/Delete in Same Page pdo6_del_list.php <!DOCTYPE html> <html> <head> <title>Add new employee</title> </head> <body> <div>Add a new employee</div> <form action="" method="post"> <p>First Name:<input type="text" name="first_name" autocomplete="off"></p> <p>Last Name:<input type="text" name="last_name" autocomplete="off"></p> <p>Email:<input type="text" name="email" autocomplete="off"></p> <p>Password:<input type="password" name="password" autocomplete="off"></p> <p><input type="submit" name="submit" value="Add"/></p> </form> </body> </html>

  16. Add/Delete in Same Page pdo6_del_list.php <?php $query = "SELECT employee_id, first_name, last_name, email FROM employees"; $stmt = $conn->query($query); echo "<table border='1'>"; echo "<tr>"; echo "<th>Employee ID</th>"; echo "<th>First Name</th>"; echo "<th>Last Name</th>"; while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo "<tr>"; echo "<td>" . $row["employee_id"] . "</td>"; echo "<td>" . $row["first_name"] . "</td>"; echo "<td>" . $row["last_name"] . "</td>"; echo "<td>" . $row["email"] . "</td>"; echo "<td><form method='POST'>\n"; echo "<input type='hidden' name='employee_id' value='". $row["employee_id"] . "'>\n"; echo "<input type='submit' name='delete' value='Delete'>\n"; echo "</td></form>"; echo "</tr>"; } echo "<th>Email Address</th>"; echo "<th>Action</th>"; echo "</tr>"; echo "</table>"; $conn = null; ?>

  17. SQL Injection SQL injection is a code injection technique, used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker). SQL injection must exploit a security vulnerability in an application's software, for example, when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and unexpectedly executed. SQL injection is mostly known as an attack vector for websites but can be used to attack any type of SQL database. (Wikipedia)

  18. login1.php <?php require_once "dbconnect.php"; if(isset($_POST["submit"])){ <!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h4>Please Login</h4> <form action="" method="post"> <p>Email:<input type="text" name="email" autocomplete="off"></p> <p>Password:<input type="password" name="password" autocomplete="off"></p> <p><input type="submit" name="submit" value="Login"/></p> </form> </body> </html> $email = $_POST["email"]; $password = $_POST["password"]; $query = "SELECT * FROM employees WHERE email = '$email' AND password = '$password'"; try{ $stmt = $conn->query($query); $row = $stmt->fetch(PDO::FETCH_ASSOC); print_r($row); if($row === false){ echo "<p>Login incorrect.</p>"; } else{ echo "<p>Login success.</p>"; } } catch(PDOException $e) { echo $query . "<br>" . $e->getMessage(); } } ?>

  19. login1.php

  20. login1.php

  21. Remedy Use Prepared Statements login2.php $query = "SELECT * FROM employees WHERE email = :email AND password = :password"; .. try{ $stmt = $conn->prepare($query); $stmt->bindParam(':email', $email); $stmt->bindParam(':password', $password); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); print_r($row); . When the statement is executed, the placeholders get replaced with the actual strings and everything is automatically escaped!

  22. Self Study Implement the Employee Edit page with PDO prepared statement

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#