Download presentation
Presentation is loading. Please wait.
1
Accessing MySQL Using PDO
2
Application Structure
Software (i.e. PHP) Database Data Model End User SQL SQL Developer Database Tools (i.e. phpMyAdmin) DBA
3
Multiple Ways to Access MySql
PHP is evolving - there are three ways to access MySql Legacy non-OO mysql_ routines (deprecated) New mysqli (OO version that is similar to mysql_) PDO - Portable Data Objects A perfect topic for debate
5
WHY PDO Database support: more than 12 databases
Connection to database server easily PDO has; binding parameters is considerably easier than using the numeric binding: Secure against Sql injection
6
Database Connection PHP Software Hostname id / password pdo.php
SQL Company Student users id / password $pdo = new PDO('mysql:host=localhost;dbname=‘company',’root', ''); pdo.php
7
Database Connection pdocon.php
<?php $host="localhost"; $db="company"; try{ $pdo= new PDO("mysql:host=$host;dbname=$db","root",""); Echo “ connected”; } catch (PDOException $e){ echo "not connected ".$e->getMessage(); die(); $pdo= null; ?> pdocon.php
8
How it works. To connect to MySQL database server, you need to create a new connection object with the data source name, user name and password. The connection object is an instance of the PDO class. If something went wrong while establishing a connection to the MySQL server, an error message will display. The try catch block is used to catch any exceptions that occurs during creating the database connection.
9
Creating Database using PHP
creatDB.php <?php $host="localhost"; try{ $pdo= new PDO("mysql:host=$host;","root",""); echo "connected" ; $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql="CREATE DATABASE Company11"; $pdo->exec($sql); echo“ database was created" ; } catch (PDOException $e){ echo “database creation error ".$e->getMessage(); die(); $pdo=null; ?> exec() method of the PDO class to execute the SQL statements in sequence. The exec() method returns the number of affected rows, including 0, on success and false on failure, PDO::ATTR_ERRMODE: Error reporting. PDO::ERRMODE_SILENT: Just set error codes. PDO::ERRMODE_WARNING: Raise E_WARNING. PDO::ERRMODE_EXCEPTION: Throw exceptions.
10
Querying a MySQL Database with PHP
The process of accessing MYSQL using PHP scripts: 1. Connect to MySQL, and Database. 2. Build a query string. 4. Perform the query. 5. Retrieve the results and output them to a web page. 6. Repeat Steps 2through 5 until all desired data has been retrieved. 7. Disconnect from MySQL
11
PDO QUERY In order to query data from database table, you have to perform the following steps: Create a connection to the database by initiating an instance of the PDO class. Pass a SQL statement to the query() method of the PDO object. This query() method returns a PDOStatement object that allows you to traverse the returned result set. If an error occurred during executing the SQL statement, the query() method return false
12
<?php $pdo = new PDO('mysql:host=localhost;dbname=‘company',’root', ''); foreach( $pdo->query("SELECT * FROM users") as $row ) { print_r($row); echo "<br />"; } ?> first.php Array( [id] => 1 [name] => ali [ ] => [password] => 123 ) [id] => 2 [name] => sam [ ] => mysql> select * from users; | id | name | | password | | 1 | ali | | | | 2 | sam | | |
13
second.php <?php $pdo = new PDO('mysql:host=localhost;dbname=company‘,'root', ''); echo '<table border="5">'."</br>"; foreach( $pdo->query("SELECT * FROM users") as $row ) { echo "<tr><td>"; echo($row['name']); echo("</td><td>"); echo($row[emiail']); echo($row[pass']); echo("</td></tr>\n"); } echo "</table>\n"; ?>
14
Pattern Put database connection information in a single file and include it in all your other files Helps make sure to not to mistakenly reveal id / pw Don't check it into a public source repository :)
15
pdocon.php <?php $host="localhost"; $db="company"; try{
$pdo= new PDO("mysql:host=$host;dbname=$db","root",""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e){ echo "not connected ".$e->getMessage(); die();
16
QueryDB.php foreach( $pdo->query("SELECT * FROM users") as $row )
require_once "pdocon.php"; foreach( $pdo->query("SELECT * FROM users") as $row ) { print_r($row); echo "<br />"; } pdo=null; ?> Array( [id] => 1 [name] => ali [ ] => [password] => 123 ) [id] => 2 [name] => sam [ ] =>
17
Inserting to DB using prepare and execute
<?php require_once‘pdocon.php'; $sql="INSERT INTO emp (name,dept, address) VALUES (:n,:dep,:add)"; $n="sam"; $add='amman'; $dep=5; $r=$pdo->prepare($sql); $r->bindParam(':n',$n,PDO::PARAM_STR); $r->bindParam(':dep',$dep,PDO::PARAM_INT); $r->bindParam(':add',$add,PDO::PARAM_STR); if ($r->execute()==true) echo "data was inserted"; else echo"error"; pdo=null; ?> PDO::prepare: prepares a statement for execution and returns a statement object. If the database server successfully prepares the statement PDO::prepare() returns object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException(depending on error handling). PDO::execute: Execute the prepared statement. If the prepared statement included parameter marker. Returns TRUE on success or FALSE on failure. Using named Placeholder
18
Inserting to DB using prepare and execute
<?php require_once‘pdocon.php'; $sql="INSERT INTO emp (name,dept, address) VALUES (?,?,?)"; $r=$pdo->prepare($sql); if ($r->execute(array("laith",5,"aqaba"))==true) echo "data was inserted"; else echo"error"; $pdo=null; ?> PDO::prepare: prepares a statement for execution and returns a statement object. If the database server successfully prepares the statement PDO::prepare() returns object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException(depending on error handling). PDO::execute: Execute the prepared statement. If the prepared statement included parameter marker. Returns TRUE on success or FALSE on failure. Using ? Placeholder
19
Lets put some data in a database!
20
InsertDBForm.php <?php require_once “pdocon.php";
if ( !empty($_POST['name']) && !empty($_POST[' ']) && !empty($_POST['pass'])) { $sql = "INSERT INTO users (name, pass, ) VALUES (:name, :pass, : )"; echo("<br />".$sql." <br />"); $stmt = $pdo->prepare($sql); if( $stmt->execute(array( ':name' => $_POST['name'], ':pass' => $_POST['pass'], ': ' => $_POST[' ']))==true) echo "one user was added"; else "eror"; } ?><html><head></head><body> <p>Add A New User</p> <form method="post"> <p>Name:<input type="text" name="name" size="40"></p> <p>Password:<input type="password" name="pass"></p> <p> <input type="text" name=" "></p> <p><input type="submit" value="Add New"/></p> </form> </body></html>
21
insertdbform1.php <?php require_once "conn.php";
if ( !empty($_POST['name']) && !empty($_POST[' ']) && !empty($_POST['pass'])) { $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); $sql = "INSERT INTO users (name, pass, ) VALUES (:name, :pass, : )"; echo("<br />".$sql." <br />"); $stmt = $pdo->prepare($sql); if( $stmt->execute(array( ':name' => $_POST['name'], ':pass' => $_POST['pass'], ': ' => $_POST[' ']))==true) echo "one user was added"; else "eror"; } ?><html><head></head><body> <table border="5"> $stmt = $pdo->prepare("SELECT name, , pass FROM users"); if ($stmt->execute()==true) { while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo "<tr><td>"; echo($row['name']); echo("</td><td>"); echo($row[' ']); insertdbform1.php echo("</td><td>"); echo($row['pass']); echo("</td></tr>"); } } else echo "error"; ?> </table> <p>Add A New User</p> <form method="post"> <p>Name:<input type="text" name="name" size="40"></p> <p>Password:<input type="password" name="pass"></p> <p> <input type="text" name=" "></p> <p><input type="submit" value="Add New"/></p> </form> </body> </html>
23
What if the id inserted is not exited?
user2del.php <?php require_once "pdocon.php"; if ( !empty($_POST['id']) ) { $sql="DELETE FROM users WHERE id = :n"; echo "$sql“.”</br>”; $stmt = $pdo->prepare($sql); $stmt->execute(array(':n'=>$_POST['id'])) echo “one user deleted”; } ?> <p>Delete A User</p> <form method="post"><p>ID to Delete:<input type="text" name="id"></p> <p><input type="submit" value="Delete"/></p> </form> What if the id inserted is not exited?
24
<?php require_once “pdocon.php"; if ( !empty($_POST['id']) ) { $sql="DELETE FROM users WHERE id = :n"; echo "<pre>\n$sql\n</pre>\n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':n'=>$_POST['id'])); if ($stmt->rowCount()>=1) echo "one user deleted"; else echo “user is not found"; } ?> <p>Delete A User</p> <form method="post"><p>ID to Delete:<input type="text" name="id"></p> <p><input type="submit" value="Delete"/></p> </form>
25
Update User <?php require_once "conn.php";
if ( !empty($_POST['id']) ) { $sql="UPDATE users SET name='ali' WHERE id = :n"; echo "<pre>\n$sql\n</pre>\n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':n'=>$_POST['id'])); if ($stmt->rowCount()>=1) echo "one row was updated"; else echo "nothing was returned"; }?> <p>Update A User</p> <form method="post"><p>ID to update:<input type="text" name="id"></p> <p><input type="submit" value=“Update"/></p> </form>
26
SQL Injection SQL injection or SQLi is a code injection technique that exploits a security vulnerability in some computer software. An injection occurs at the database level of an application (like queries). The vulnerability is present 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. Using well designed query language interpreters can prevent SQL injections.
27
The Problem – What is SQL Injection
SQL Injection is quite simply, when the user injects SQL into your application. How does this happen? Say we have a nice simple login form that takes a username and password, and checks if that’s in the database. If it is, the user is logged into an admin section or something. The code for this could look something like this
28
Problem what happens if I enter my username and password as this?
The query that gets sent to MySQL will look like this: SELECT name FROM users WHERE name ='' OR ''='' AND pass='' OR ''='' What does this mean? It tells MySQL to find all rows with a username equal to “” or empty is equal to empty and a password equal to an empty string OR empty equal to empty. To represent that a bit more logically: (false or true )and (false or ture ) Which means that ALL the records in the table will get returned. Our login processer above is going to log me on with someone else’s credentials – in fact, those of the first record returned. Keep in mind, however, that we don’t need to escape numbers, and we shouldn’t put quote marks around them (it’s not standard SQL)- if a variable is a number, then it’ll be fine.
29
The above statement will return all ids of users from databases
31
SQL Injection This code is prone to SQL Injection - where? Magic ‘or ‘’=‘ in the password input form <?php require_once'conn.php'; if ( !empty($_POST['name']) && !empty($_POST['pass']) ) { $e = $_POST['name']; $p = $_POST['pass']; $sql = "SELECT * FROM users WHERE name= '$e' AND pass= '$p'"; foreach( $pdo->query($sql) as $row) echo$row['name']."<br />" ; } ?> <form method="post"> UserName: <input type="text" name="name" maxlength="12" /> <br/> Password: <input type="password" name="pass" maxlength="8" /> <br/> <input type="submit" name="submit" /> </form> Note: For PHP < 5.4 – this might not fail, actually – look up "stripslashes"
32
Use Prepared Statements Properly
login2.php <?php if ( !empty($_POST['name']) && !empty($_POST['pass']) ) { require_once 'conn.php'; $stmt = $pdo->prepare("SELECT * FROM users WHERE name=:n AND pass=:p "); $stmt->execute(array('n'=>$_POST['name'], 'p'=>$_POST['pass'])) ; echo $stmt->rowCount(); if ($stmt->rowCount()==1) header("location:UpdateDbForm.php"); else echo "user name or password invlaid"; } ?> <form method="post"> UserName: <input type="text" name="name" maxlength="12" /> <br/> Password: <input type="password" name="pass" maxlength="8" /> <br/> <input type="submit" name="submit" /> </form> When the statement is executed, the placeholders get replaced with the actual strings and everything is automatically escaped!
33
CRUD Pattern When we store things in database tables we generally need
Create - Insert a new row Read - Read existing row(s) Update - Change some values of a record Delete - Delete a record So far we have done 3/4 of CRUD
34
Five Separate Files index.php - Main list and links to other files
add.php - Add a new entry within index delete.php - Delete an entry edit.php - Edit existing
35
index.php <?php require_once "conn.php";
if ( !empty($_POST['name']) && !empty($_POST[' ']) && !empty($_POST['pass'])) { $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); $sql = "INSERT INTO users (name, pass, ) VALUES (:name, :pass, : )"; echo("<br />".$sql." <br />"); $stmt = $pdo->prepare($sql); if( $stmt->execute(array( ':name' => $_POST['name'], ':pass' => $_POST['pass'], ': ' => $_POST[' ']))==true) echo "one user was added"; else "eror"; } ?><html><head></head><body> <table border="5"> <?php $stmt = $pdo->prepare("SELECT id,name, , pass FROM users"); if ($stmt->execute()==true) { while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo "<tr><td>"; echo($row['name']); echo("</td><td>"); echo($row[' ']); echo($row['pass']); echo '<a href="deleteindex.php?id='.$row['id'].'">delete</a>'; echo '<a href="editindex.php?id='.$row['id'].'">edit</a>'; echo("</td></tr>"); } } else echo "error"; ?>
36
</table> <p>Add A New User</p> <form method="post"> <p>Name:<input type="text" name="name" size="40"></p> <p>Password:<input type="password" name="pass"></p> <p> <input type="text" name=" "></p> <p><input type="submit" value="Add New"/></p> </form> </body> </html>
37
Delete.php <?php require_once "conn.php";
if ( !empty($_GET['id']) ) { $sql="DELETE FROM users WHERE id = :n"; echo "<pre>\n$sql\n</pre>\n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':n'=>$_GET['id'])); if ($stmt->rowCount()>=1) { echo "one user deleted"."<br />"; echo '<a href="index.php">go back to index</a>'; } else { echo “id is invalid"."<br />"; } ?> Delete.php
38
editindex.php <h3> the user id that you wish to edit
<?php echo $_GET['id']."<br />";?></h3> <form method="post" action="editIndexDivert.php"> <?php require_once "conn.php"; if ( !empty($_GET['id']) ) { $stmt = $pdo->prepare("SELECT id,name, , pass FROM users WHERE id='$_GET[id]' "); if ($stmt->execute()==true) { while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { ?><p> <input type="text" value="<?php echo($row['id']);?>" readonly name="id1"/></p> <p><input type="text" value="<?php echo($row['name']);?>" name="n"/></p> <p><input type=" " value="<?php echo($row[' ']);?>" name="e"/></p> <p><input type="password" value="<?php echo($row['pass']);?>" name="p"/></p> <input type="submit" value="Update" /> } } else echo "error"; }?> </form>
39
editIndexDiverted.php <?php require_once "conn.php";
if ( !empty($_POST['id1']) ) { $sql="UPDATE users SET name='$_POST[n]', ='$_POST[e]',pass='$_POST[p]' WHERE id = :n"; echo "<pre>\n$sql\n</pre>\n"; $stmt1 = $pdo->prepare($sql); $stmt1->execute(array(':n'=>$_POST['id1'])); if ($stmt1->rowCount()==1) { echo "one row was updated"; echo '<a href="index.php">go back to index</a>'; } else { echo "id is invalid"; echo '<a href="index.php">go back to index</a>'; } } ?> editIndexDiverted.php
40
Summary Making database connections Doing database operations
SQL security (a.k.a. we love PDO prepared statements) A multi-file CRUD application with redirect
41
Acknowledgements / Contributions
Continue new Contributors and Translators here These slides are Copyright Charles R. Severance ( as part of and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information Insert new Contributors and Translators here including names and dates Note from Chuck. Please retain and maintain this page as you remix and republish these materials. Please add any of your own improvements or contributions.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.