I’m still pretty new and am having some trouble trying to figure out how to include a name to a delete confirmation. I understand that I need to insert an echo after the delete message but am having some trouble on how to set this up code-wise. Any help in explaining would be appreciated.
Code below:
delete.php
<?php
require("database.php");
$id = 0;
if (!empty($_GET["id"])) {
$id = $_REQUEST["id"];
}
if (!empty($_POST)) {
// Keep track of post values
$id = $_POST["id"];
// Delete data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "DELETE FROM customers WHERE id = ?";
$stmt = $pdo->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
Database::disconnect();
header("Location: index.php");
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<link href="http://localhost/projects/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="http://localhost/projects/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1></h1>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Delete a Customer</h3>
</div>
<form class="form-horizontal" action="delete.php" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p class="alert alert-error">Are you sure you want to delete?</p>
<div class="form-actions">
<button type="submit" class="btn btn-danger">Yes</button>
<a class="btn" href="index.php">No</a>
</div>
</form>
</div>
</div> <!-- container end -->
</body>
</html>
database.php
<?php
class Database {
private static $dbName = "crud_tutorial";
private static $dbHost = "localhost";
private static $dbUsername = "root";
private static $dbPassword = "";
private static $connection = null;
public function __construct() {
die("Init function is not allowed");
}
public static function connect() {
// One connection through whole application
if (null == self::$connection) {
try {
self::$connection = new PDO("mysql: host=" . self::$dbHost . ";" . "dbname=" .
self::$dbName, self::$dbUsername, self::$dbPassword);
} catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$connection;
}
public static function disconnect() {
self::$connection = null;
}
}
?>
Took the liberty of cleaning up some of your code. It is still far from ideal but that said for a beginner the changes shouldn’t be to problematic to understand. I also added comments. Probably couldn’t hurt to add some error handling with try catch but was trying to keep the refactoring as simple as possible.
<?php
require 'database.php';
require 'customer.php';
// initiate db connection
$db = Database::connect();
$customer = NULL;
if (isset($_GET["id"])) {
$customer = load_customer($db,$_GET['id']);
if(!$customer) {
exit; // Probably best to add some type of error handling here when requested customer can't be found.
}
}
if (isset($_POST['id'])) {
$success = delete_customer($db,$_POST["id"]);
if(!$success) {
exit; // Probably best to add some type of error handling here is the customer is not deleted.
}
header("Location: index.php");
}
// template vars
$tpl = array(
'confirm_msg'=> 'Are you sure you want to delete '.htmlspecialchars($customer->name).'?',
'customer_id'=> $customer->id,
);
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<link href="http://localhost/projects/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="http://localhost/projects/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1></h1>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Delete a Customer</h3>
</div>
<form class="form-horizontal" action="delete.php" method="post">
<input type="hidden" name="id" value="<?php echo $tpl['customer_id']; ?>" />
<p class="alert alert-error"><?php echo $tpl['confirm_msg']; ?></p>
<div class="form-actions">
<button type="submit" class="btn btn-danger">Yes</button>
<a class="btn" href="index.php">No</a>
</div>
</form>
</div>
</div> <!-- container end -->
</body>
</html>
customer.php
// Customer data access functions
/**
* Load customer by primary key.
*
* @param PDO $db
* The PDO instance. Ideally we would using some type of dependency injection
* but keeping it simple. Having to pass the connection into each and every
* data access function sucks...
*
* @param int $id
* The customer primary key.
*
* @return StdClass
* The customer domain object represented as a StdClass for simplicity.
*/
function load_customer(PDO $db, $id) {
$stmt = $db->prepare('SELECT * FROM customers WHERE id = :id');
$result = $stmt->execute(array(':id'=> (int) $id));
$customer = $result->fetchObject();
return $customer === FALSE?NULL:$customer;
}
/**
* Delete customer by ID.
*
* @param PDO $db
* The database connection instance.
*
* @param int $id
* Primary key of customer to delete.
*
* @return bool
* Whether operation was sucessful of not.
*/
function delete_customer(PDO $db, $id) {
$stmt = $db->prepare('DELETE FROM customers WHERE id = :id');
$stmt->execute(array(':id'=> (int) $id));
return (bool) $stmt->rowCount();
}
The main idea with the customer.php file would be to place any functions that deal with business logic for customers. This makes all the logic reusable so that it can be used again if need be in other places of the site. Ideally I would use a repository class and domain objects but that starts to become a deep dive into OOP and ORM’s. So I was attempting here to provide you with some pathway to separation of concerns without getting to caught up in OOP, ORM’s, MVC, etc. There could probably be a considerable more amount of clean-up when it comes to separation of concerns and managing forms in general though again that starts to get into more intermediate/advanced concepts of creating reusable classes/frameworks for common patterns such as form management. Where in most cases if you were using some type of framework like most of us are these days there is already a considerable number of the things I’m referring to present already.