Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
PDO Delete and Update PHP Scripts 1.0 2.0 3.0 4.0 Creating a Delete PDO Query............................................................................. 1 Modifying the PDO Select Script ....................................................................... 5 Creating an Update PDO Query ......................................................................... 8 Closing the connection to the MySQL database ............................................... 13 PDO Delete and Update PHP Scripts Ivailo Chakarov PDO Delete and Update PHP Scripts 1.0 Creating a Delete PDO Query In your previous sessions you learnt how to open and close a connection to a MySQL database using PDO as well as learnt how to create a PDO Insert and Select PHP scripts. This handout examines how you can create PDO Delete and Update PHP scripts. Although we are using MySQL, considering that PDO provides a common set of tools for databases, once we have the correct connection established, the rest of the code can be used regardless of the type of database that we have chosen (Source: Introduction to PHP PDO). Here is an example PHP file (delete_employee.php) which is used to delete an employee record from the employee table of your employeeproject database. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Delete An Employee</title> </head> <body> <?php //setting the database connection parameters $servername = "localhost"; $username = "root"; $password = ""; $dbname = "employeeproject"; PDO Delete and Update PHP Scripts 1 Ivailo Chakarov //initialise a parameter which would be set up to pass the employee's number to be deleted $employeeid = ""; //check whether the parameter of the employee's id has been specified when the Delete PHP script is called if(isset($_GET['id'])) { $employeeid = $_GET["id"]; } //if the id of the employee has not been specified a default emp_no of 12 is being used else { $employeeid = '12'; } try { //creating the database connection object $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); //prepare the sql statement which returns how many employees match this employee id $selected_employee = "SELECT COUNT(*) FROM Employee WHERE Emp_No='$employeeid'"; //prepare the select statement to be executed $no_of_employees = $conn->prepare($selected_employee); //prepare the sql statement to delete a record $delete_sql = "DELETE FROM Employee WHERE emp_no='$employeeid'"; /*prepare the select statement to return the number of projects (if any which the specific selected employee has allocated against their name */ $no_of_projects = "SELECT COUNT(*) FROM Emp_On_Project WHERE Emp_No='$employeeid'"; PDO Delete and Update PHP Scripts 2 Ivailo Chakarov //execute the no_of_projects query if ($res2 = $conn->query($no_of_projects)) { /* Check the number of rows that match the SELECT statement */ if ($res2->fetchColumn() > 0) { //if the number of projects allocated against the selected employee is more than zero //then issue a warning - i.e. you must delete the projects first before deleting the //employees! - the foreign key constraint will stop you executing the DELETE query! echo "<b>Warning!</b><p>"; echo "There are project allocations for <b>Emp_No $employeeid</b>."; echo "You must delete the employee allocations first before deleting the employee!</p>"; echo "<p><a href='select_all_employees.php'>Display All Employees</a> "; echo "<a href='insert_new_employee.php'>Insert New Employee</a></p>"; } //otherwise you can prepare to delete the chosen employee from the employee table of the database else { //executed the query to find out how many employees match this employee id if ($res = $conn->query($selected_employee)) { /* Check the number of rows that match the SELECT statement */ if ($res->fetchColumn() > 0) { //if more than one row is returned then execute the delete query // use exec() because no results are returned $count = $conn->exec($delete_sql); /* Delete statement executed */ print("You executed the following SQL statement: <b>$delete_sql</b><br />"); PDO Delete and Update PHP Scripts 3 Ivailo Chakarov /* Return number of rows that were deleted */ print("<p>Deleted $count rows from the employee table.</p>"); } /* No rows matched -- do something else */ else { /* Return the message below */ print "No rows matched the query."; } } //display the links at the bottom of the page to the other two php pages echo "<p><a href='select_all_employees.php'>Display All Employees</a> "; echo "<a href='insert_new_employee.php'>Insert New Employee</a></p>"; } } } //deal with any PDO connection execeptions. catch(PDOException $e) { echo $selected_employee . "<br>" . $e->getMessage(); } $res = null; //close the database connection $conn = null; ?> </body> </html> PDO Delete and Update PHP Scripts 4 Ivailo Chakarov 2.0 Modifying the PDO Select Script Please modify your PDO Select PHP script which you have created in the previous session (changes are highlighted in different colour): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Display All Employees</title> </head> <body> <?php //setting the database connection parameters $servername = "localhost"; $username = "root"; $password = ""; $dbname = "employeeproject"; try { //creating the database connection object $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); //prepare the SELECT statement to choose all employees $employees = $conn->prepare("SELECT * FROM employee"); //execute the SELECT statement $employees->execute(); PDO Delete and Update PHP Scripts 5 Ivailo Chakarov //display all the records from the employees table in a table format. echo "<h2>Display all employee records</h2>"; echo "<table border='1'>"; echo "<tr>"; //print out the Emp_No heading echo "<td width='50'>Emp_No</td>"; //print out the Emp_fname heading echo "<td width='100'>Emp_fname</td>"; //print out the Emp_sname heading echo "<td width='100'>Emp_sname</td>"; //print out the Grade heading echo "<td>Grade</td>"; //print out the Update heading echo "<td>Update?</td>"; //print out the Delete heading echo "<td>Delete?</td>"; echo "</tr>"; //loop over all table rows and fetch them as an object while($result = $employees->fetch(PDO::FETCH_OBJ)) { //print out the details of each employee echo "<tr>"; PDO Delete and Update PHP Scripts 6 Ivailo Chakarov //print out the Employee's No echo "<td width='50'>" . $result->Emp_No . "</td>"; //print out the Employee's First Name echo "<td width='100'>" . $result->Emp_fname . "</td>"; //print out the Employee's Surname echo "<td width='100'>" . $result->Emp_sname . "</td>"; //print out the Employee's Grade echo "<td>" . $result->Grade . "</td>"; //print out the Update option echo "<td align='center'>" . "<a href='update_employee.php?id=$result->Emp_No'>X</a>" . "</td>"; //print out the Delete option echo "<td align='center'>" . "<a href='delete_employee.php?id=$result->Emp_No'>X</a>" . "</td>"; echo "</tr>"; echo("\n"); } echo "</table>"; //link this PHP file to the PDO Insert script (insert_new_employee.php) echo "<p>"; echo "<a href='insert_new_employee.php'>Insert a new employee record</a>"; echo "</p>"; //close the database connection $conn = null; } //deal with any PDO connection execeptions. PDO Delete and Update PHP Scripts 7 Ivailo Chakarov catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?> </body> </html> 3.0 Creating an Update PDO Query Here is an example PHP file (update_employee.php) which is used to delete an employee record from the employee table of your employeeproject database. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>Delete An Employee</title> </head> <body> <?php // define variables and set to empty values $employee_no = $employee_firstname = $employee_surname = $employee_grade = ""; //setting the database connection parameters $servername = "localhost"; $username = "root"; $password = ""; $dbname = "employeeproject"; PDO Delete and Update PHP Scripts 8 Ivailo Chakarov $employeeid = "12"; //if the POST method is used to submit the update form then the employee id is set to the one //specified in the Employee No text field in the form if ($_SERVER['REQUEST_METHOD'] === 'POST') { $employeeid = test_input($_POST["emp_no"]); } //if the GET method was used to call the update PHP script from a different page then if ($_SERVER['REQUEST_METHOD'] === 'GET') { //check whether the parameter of the employee's id has been specified when the Delete PHP script is called if(isset($_GET['id'])) { $employeeid = $_GET["id"]; } //if the id of the employee has not been specified a default emp_no of 12 is being used else { $employeeid = '12'; } } try { //creating the database connection object $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); //prepare the SELECT statement to choose all employees matching the Employee ID $selected_employee = $conn->prepare("SELECT * FROM Employee WHERE Emp_No='$employeeid'"); //execute the SELECT statement $selected_employee->execute(); //prepare a SELECT statement to return the pay grade which the chosen employee is on PDO Delete and Update PHP Scripts 9 Ivailo Chakarov $selected_grade = $conn->prepare("SELECT Grade FROM Employee WHERE Emp_No='$employeeid'"); //exectute the query $selected_grade->execute(); //prepare the SELECT statement to return all possible grades $grades = $conn->prepare("SELECT * FROM Pay_Structure"); //execute the SELECT statement $grades->execute(); //save the employee's grade in a variable to be used for displaying the right option //in the select drop down menu $employee_grade = $selected_grade->fetchColumn(); //if the form was submitted (using the POST method) if ($_SERVER["REQUEST_METHOD"] == "POST") { //collect all the form entries and store them in variables $employee_no = test_input($_POST["emp_no"]); $employee_firstname = test_input($_POST["emp_fname"]); $employee_surname = test_input($_POST["emp_sname"]); $employee_grade = test_input($_POST["emp_paygrade"]); //prepare the UPDATE statement (using the modified values that the user has changed to) $update_sql = "UPDATE employee SET emp_no='$employee_no', emp_fname='$employee_firstname', emp_sname='$employee_surname', grade='$employee_grade' WHERE emp_no=$employee_no"; //execute the UPDATE statement if ($conn->exec($update_sql)) { //display confirmation that the record has been updated successfully. echo "Your record updated successfully."; } else { PDO Delete and Update PHP Scripts 10 Ivailo Chakarov //echo the update statement error which is generated if the statement fails; echo "Error: " . $update_sql. "<br>" . $conn->error; } //close the database connection $conn = null; } } //deal with any PDO connection execeptions. catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } //the function test_input strips any blanks, special characters, //etc. and returns back the cleaned data function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h3>Update an Employee</h3> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="new_employee"> <?php while($result = $selected_employee->fetch(PDO::FETCH_OBJ)) { PDO Delete and Update PHP Scripts 11 Ivailo Chakarov //display the values returned from the SELECT query in the text fields of the form //Make the employee No readonly (i.e. the user will not be able to change the employee no in the form!) echo 'Employee No (Readonly) <input name="emp_no" type="text" size="11" maxlength="11" value="' .$result->Emp_No .'" readonly/><br />'; echo 'First Name <input name="emp_fname" type="text" size="35" maxlength="80" value="' .$result->Emp_fname . '" /><br />'; echo 'Surname <input name="emp_sname" type="text" size="35" maxlength="80" value="' .$result->Emp_sname . '"/> <br />'; echo 'Grade '; echo '<select name="emp_paygrade">'; //display all the available values for grades in the drop down menu while($result2 = $grades->fetch(PDO::FETCH_OBJ)) { echo '<option value="'. $result2->Grade .'"'; //if the Grade number matches the grade number of the specific chosen employee if ($result2->Grade == $employee_grade) { //then select it ! echo ' selected '; } echo '>'. $result2->Grade .'</option>'; } echo '</select>'; } ?> <p></p> <input type="reset" name="reset" /> <input type="submit" name="submit" /> </form> PDO Delete and Update PHP Scripts 12 Ivailo Chakarov <?php //link this PHP file to the PDO Select script (select_all_employees.php) echo "<p>"; echo "<a href='select_all_employees.php'>Display all employee records</a>"; echo "</p>"; ?> </body> </html> 4.0 Closing the connection to the MySQL database The connection to the database would need to be closed by using the following statement: $conn = null; PDO Delete and Update PHP Scripts 13 Ivailo Chakarov