Web Technologies – CS 382 CONTENTS ⦿ MySql Database & PhpMyAdmin ⦿ Connecting with database ⦿ Executing queries ⦿ Performing transactions ⦿ Performing actions based on query result ⦿ Securing database ◼ Preventing SQL injection ◼ Securing passwords Database Basics ⦿ Every DBMS is installed on some Host (same or remote) ⦿ Every DBMS may have multiple Databases ⦿ Access of a database is defined in user rights ⦿ Every DBMS may have multiple users ⦿ Each user must be protected by password ⦿ One user may have right to multiple databases ⦿ So to connect with a database ◼ Host name is required (may be IP address) ◼ Database name to which you want to connect ◼ User name that has right to the database ◼ Password of that user name to authenticate MySql & PhpMyAdmin – case study ⦿ Creating database & tables ⦿ Creating users ⦿ Taking backup ⦿ Restoring backups ⦿ Case study ◼ Create a database named plant_nursery ◼ Create a table for users ◼ Create a table for products MySql Database with PHP ⦿ MySql extension of PHP (Old, should not use) ⦿ MySqli extension of PHP (new, may use) ⦿ PHP Data Objects (PDO) (may use) ◼ PDO are wrappers to connect with any database (MySqli, Postgre SQL, SYS Base, IBM DB2, Oracle Database) ◼ Other databases can also be used like MS SQL, Cubrid, DB++, dBase, filePro, FireBird/InterBase, FrontBase, Infromix, Ingres, MaxDB, Mongo, Ovrimos SQL, Paradox, SQLite, SQLite3, SQLSRV, Tokyo Tyrant How to Connect ⦿ Create the MySqli Object, and pass the parameters ◼ $db = new mysqli(‘host’, ‘username’, ‘password’, ‘dbname’, ‘port’, ‘socket’); ◼ Or use connect method ⦿ Check that connection is established or not ◼ If($db->connect_errno>0) { die($db->connect_error);} ⦿ Example $db = new mysqli(); $db->connect(‘localhost’, ‘root’, ‘’, ‘forum’); If($db->connect_errno>0) { die (“Unable to connect ”.$db->connect_error); } How Insert ⦿ You must have query to execute ◼ $sql = ‘some insert query’; ⦿ Execute the query ◼ $db->query($sql); ⦿ Check for success ◼ If($db->errno>0) { die($db->error);} ⦿ Example $sql = “INSERT INTO users (name, password) VALUES (’Ali’, ‘123’)”; $db->query($sql); If($db->errno>0) { die (“Unable to insert ”.$db->error); } else { echo $db->insert_id; //get the insert row auto increment key if any echo $db->affected_rows; //how many rows are inserted } Case study - Save Registrations ⦿ Duplicate the users table and do necessary changes ⦿ Modify the signup page and save the user registration in application table ⦿ Handle the database errors ⦿ Make sure that no user or same application exist ⦿ DP file should be named with user auto increment key ⦿ Use transactions to ensure data correctness ⦿ Save password securely ⦿ Ensure database safety by preventing sql injections How Update ⦿ You must have query to execute ◼ $sql = ‘some update query’; ⦿ Execute the query ◼ $db->query($sql); ⦿ Check for success ◼ If($db->errno>0) { die($db->error);} ⦿ Example $sql = “UPDATE users SET name=‘Usama’ WHERE id=1”; $db->query($sql); If($db->errno>0) { die (“Unable to update”.$db->error); } else { echo $db->affected_rows; //how many rows are updated } How Delete ⦿ You must have query to execute ◼ $sql = ‘some Delete query’; ⦿ Execute the query ◼ $db->query($sql); ⦿ Check for success ◼ If($db->errno>0) { die($db->error);} ⦿ Example $sql = “DELETE FROM users WHERE id=1”; $db->query($sql); If($db->errno>0) { die (“Unable to delete ”.$db->error); } else { echo $db->affected_rows; //how many rows are deleted } How Select ⦿ You must have query to execute ◼ $sql = ‘some select query’; ⦿ Execute the query and get result set ◼ $result = $db->query($sql); ⦿ Loop through the result set to process and free it echo $result->num_rows; //tells how many rows are selected while(($row = $result->fetch_array())) { echo $row[0].’ ‘.$row[1]; //etc } $result->free(); ⦿ Use $result->fetch_array(MYSQLI_ASSOC) to fetch associative array ⦿ Use $result->fetch_array(MYSQLI_NUM) to fetch numeric indexed array ⦿ Use $result->fetch_row() to fetch numeric indexed array ⦿ User $result->fetch_assoc() to fetch associative array ⦿ Use $result->fetch_object() to fetch row as object How Close connection ⦿ Close the connection ◼ $db->close(); Transactions in Database ⦿ What are Transactions ◼ Execute multiple queries that are related ◼ If any query fail whole changes should be discarded ◼ If all queries are successful then changes must be saved ◼ It Locks the table ⦿ Three Steps ◼ Start Transaction ◼ Execute queries ◼ Complete or Rollback the transaction ⦿ Start Transaction ◼ $db->autocomit(bool); //return bool ⦿ Complete the transaction (successful case) ◼ $db->commit(); //returns bool ⦿ Roll back transaction (failure case) ◼ $db->rollback(); //returns bool Prevent SQL Injection ⦿ User gives input that can change the meaning of query. ⦿ Simple rule, do not trust anything coming from user ◼ Escape the user input to use in database queries ◼ $someinput = mysqli_real_escape_string($db, $someinput) ⦿ SQL Injection Examples $sql = “DELETE FROM users WHERE id=“.$user_id; $sql = “SELECT * FROM users WHERE username=‘”.$user.”’ AND pass=‘”.$pas.”’; Don’t save Plain Password ⦿ Use MD5 Encryption (not safe today) ⦿ Bcrypt (used today, not reversable) ◼ $options = array(“cost”=>8); ◼ $hashedpwd = password_hash($password, PASSWORD_BCRYPT, $options) ◼ password_verify($password, $hash) //to match Don’t Expose db structure ⦿ When there is an error or something, do not show executed query ⦿ Never show table names, field names or some rules that can expose your database structure Reading ⦿ Book ◼ Beginning PHP & MYSQL From Novice to Professional Chapter 30