SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Member
    Join Date
    Oct 2013
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Need some guidance on including "name" for delete confirmation message

    Hi All,

    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 Code:
    <?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_ERRMODEPDO::ERRMODE_EXCEPTION);
            
    $query "DELETE FROM customers WHERE id = ?";
            
    $stmt $pdo->prepare($query);
            
    $stmt->bindValue(1$idPDO::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 Code:
    <?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::$dbNameself::$dbUsernameself::$dbPassword);
                } catch(
    PDOException $e) {
                    die(
    $e->getMessage());
                }
            }
            return 
    self::$connection;
        }
        public static function 
    disconnect() {
            
    self::$connection null;
        }
    }
    ?>

  2. #2
    SitePoint Member
    Join Date
    Oct 2013
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You'd need to query the db to get it i'd guess

  3. #3
    SitePoint Member
    Join Date
    Oct 2013
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Thumbs up

    Quote Originally Posted by looped View Post
    You'd need to query the db to get it i'd guess
    Yes, resolved with the help of the author of the tutorial. (http://www.lizardgrid.com/blog/php-c...torial-part-1/)

    Missing code to get the $name information to be echoed out:
    PHP Code:
        if (!empty($_GET["id"])) {
             
    $id   $_REQUEST["id"];

            
    $pdo Database::connect();
            
    $pdo->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
            
    $sql "SELECT * FROM customers where id = ?";
            
    $q $pdo->prepare($sql);
            
    $q->execute(array($id));
            
    $data $q->fetch(PDO::FETCH_ASSOC);
            
            
    //get $name value
            
    $name $data['name'];
            
    Database::disconnect();
        } 

  4. #4
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,048
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    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 Code:
    <?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
    PHP Code:
    // 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.
    The only code I hate more than my own is everyone else's.

  5. #5
    SitePoint Member
    Join Date
    Oct 2013
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Appreciate the time for the clean up and explanation for everything. Much appreciated. Now I need to soak it in.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •