Bazaar – php example code – part 3 – Manage category script

Article focus on way how we populate category/ subcategory for selling items. Management page contains listing of scucessfully added fileds with removal link as option. Our project will lead from category, trough item, simple login functionality into a editprofile option with more robust user login.

Discuss managecategory.php functionality

Our managecategory.php script must enable these functionalities:

  • create subcategory of item with existing main category
  • if we creating subcategory with non existing man category, we must be able to add them along
  • after all succesfully added category, list of existing category/ subcategory must be displayed with link for removal appropriate category row
  • after preparing parts for login verification, these scripts can be viable only for user with admin role assigned by page admin

Visual content of this page along with removecategory.php script follow:

Visual look of managecategory.php script

Category romoval script confirmation dialog

Implementation of expected functionality

Our page consist from parts for obtain user category and subcategory names. Error messaging, reporting of successfull category addition into bazaar_category table are next parts of our script.

Form obtaining data from user follow next:

 <form  method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>„>
          <div class=“form-group“>
              <label>* Set name for new subcategory:</label>
              <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚subcategory‘]) ? $subcategory : “; ?>'“ name=“subcategory“ class=“form-control“ value=“<?php echo isset($_POST[‚subcategory‘]) ? $subcategory : ‚Please provide name of new subcategory‘; ?>“>
              <br> 
              <label>* Select main category for nesting created subcategory:</label>
              <input list=“category“ name=“category“ >
                <datalist id=“category“>
                    <?php // here read data from mysql bazaar_category and display existing category whre subcategory will be nested
                        $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

 

                            // Check connection
                             if($dbc === false){
                                 die(„ERROR: Could not connect to database. “ . mysqli_connect_error());
                             };
                         
                         
                            
             
                            // create SELECT query for category names from database
                            $sql = „SELECT DISTINCT category FROM bazaar_category ORDER BY category ASC„;

 

                            // execute sql and populate data list with existing category in database
                            if($output = mysqli_query($dbc, $sql)){
                                if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
                                    
                                    while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                                    
                                            echo „<option value=“ . $row[‚category‘] . „>„;
                                                                              
                                    }
                                    
                                    // Free result set
                                    mysqli_free_result($output);
                                } else{
                                    echo „There is no category in category table. Please wirite one.“; // if no records in table
                                }
                            } else{
                                echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
                            }
 
                            // Close connection
                            mysqli_close($dbc);
                    ?>
                   
                    
                </datalist>
              <br> 
              
              <button type=“submit“ name=“subcategorysubmit“ class=“btn btn-warning“> Create new subcategory </button>
              <input type=“reset“ class=“btn btn-info“ value=“Reset“>             
          </div>
          <hr> 
          </form> 
             
    
          
          
          <br><br>
          
          
          <?php   //part displaying info after succesfull added category into a mailinglist
                 if ($is_result ) {
  
                        echo „<br> <br>“;
                        echo “ <table class=\“table table-success\“> „;
                        echo “ <tr>
                               <td><h5> <em> Category: </em> $category with subcategory $subcategory </h5> <h5> has been succesfully added to category list </h5> „;
                                  
                        
                          
                        echo “     <td>   </tr> „; 
                        echo “ </table> „;
                    
                    //echo “ <input type=“text“ id=“result_field“ name=“result_field“ value=“$result“  >  <br>“ ;
                } ; 
                 ?>
                 <br>
        
      </form>
      <?php

Listening of all items in bazaar_category table is generated by this content of script

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

// Check connection
if($dbc === false){
    die(„ERROR: Could not connect to database – stage of article listing. “ . mysqli_connect_error());
}
    
            
// read all rows (data) from guestbook table in „test“ database
$sql = „SELECT * FROM bazaar_category ORDER BY category ASC, subcategory ASC„; 
/********************************************************************/
/*    Output in Table – listening all category in bazaar_category table       */
/********************************************************************/
// if data properly selected from guestbook database tabele

echo „<h4>List of active categories and subcategories</h4>“;
echo „<br>“;
echo ‚ <button class=“btn btn-secondary btn-lg “ onclick=“location.href=\’admin.php\'“ type=“button“>  admin page -> </button>‘;

echo „<br>“; echo „<br>“;

    if($output = mysqli_query($dbc, $sql)){
        if(mysqli_num_rows($output) > 0){  // if any record obtained from SELECT query
            // create table output
            echo „<table>“; //head of table
                echo „<tr>“;
                    echo „<th>subcategory_id</th>“;
                    echo „<th>category</th>“;
                    echo „<th>subcategory</th>“;
                    echo „<th></th>“;
                    echo „<th>delete category</th>“;
                    
                    
                    
                    
                echo „</tr>“;
            while($row = mysqli_fetch_array($output)){ //next rows outputed in while loop
                echo “ <div class=\“mailinglist\“> “ ;
                echo „<tr>“;
                    echo „<td>“ . $row[‚subcategory_id‘] . „</td>“;
                    echo „<td>“ . $row[‚category‘] . „</td>“;
                    echo „<td>“ . $row[‚subcategory‘] . „</td>“;
                     // removal line with removing link line
                
                     
                     echo „<td  colspan=\“1\“> Manage entry: </td>“; // description on first line
                         echo ‚<td colspan=“1″><a id=“DEL“ href=“removecategory.php?subcategory_id=‘.$row[‚subcategory_id‘] . ‚&amp;category=‘
                         . $row[‚category‘] . ‚&amp;subcategory=‘. $row[‚subcategory‘] .'“> >> Remove  </a></td></tr>‘; //construction of GETable link
                         // for removecategory.php input
                    
                    
                echo „</tr>“;
                echo “ </div> “ ;
            }
            echo „</table>“;
            // Free result set
            mysqli_free_result($output);
        } else{
            echo „There is no benchmark result in chart. Please wirite one.“; // if no records in table
        }
    } else{
        echo „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc); // if database query problem
    }

// Close connection
mysqli_close($dbc);
?>
      

removecategory.php script

Remove category script obtain data from GET associative array ofered from url snipet added to name of invoked page. After reading data, cerate removal confirmation form.

After selecting yes and submitting form, appropriate category/ subcategory row is removed with approrpiate sql query.

Content of the page is in following part:

<!– *************************************************************** –>
<!– PHP „self“ code GET request for remove and POST delete data         –>
<!– *************************************************************** –>
<!– Vrsion: 1.0        Date: 17.10.2020 by CDesigner.eu                                   –>
<!– *************************************************************** –>

 

<?php // leading part of page for simple header securing and basic variable setup
    require_once(‚appvars.php‘); // including variables for database
    session_start(); // start the session – must be added on all pages for session variable accessing – further description will be available in appropriate article in a row of articles focused on bazaar app

 

  // solution using SESSIONS with COOKIES for longer (30days) login persistency
    
  if(!isset($_SESSION[‚users_id‘])) { // if session is no more active
    if(isset($_COOKIE[‚users_id‘]) && isset($_COOKIE[‚username‘])) { // but cookie is set then renew session variables along them
      $_SESSION[‚users_id‘] = $_COOKIE[‚users_id‘];
      $_SESSION[‚username‘] = $_COOKIE[‚username‘];
    }
   }
   
  // two variables for message and styling of the mesage with bootstrap
  $msg = “;
  $msgClass = “;

 

  // default values of auxiliary variables
  
?>

 

<!– ******************************************* –>
<!– script for appropriate scode removal        –>
<!– ******************************************* –>
<!– obtain GET data from admin.php and trough   –>
<!– POST submit remove data from database       –>
<!– ******************************************* –>
<!DOCTYPE html>
<html>
<head>
  <title> Bazaar score – remove script </title>
  <link rel=“stylesheet“ href=“./css/bootstrap.min.css“> <!– bootstrap mini.css file –>
  <link rel=“stylesheet“ href=“./css/style.css“> <!– my local.css file –>
    <script src=“https://code.jquery.com/jquery-3.1.1.slim.min.js“ integrity=“sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n“ crossorigin=“anonymous“></script>
        <script src=“https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js“ integrity=“sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb“ crossorigin=“anonymous“></script>
  
</head>
<body>
  <nav class=“navbar navbar-default“>
      <div class=“container“>
        <div class=“navbar-header“>    
          <a class=“navbar-brand“ href=“managecategory.php“>Bazaar category manager – part for Bazaar category management</a>
          <a class=“navbar-brand“ href=“index.php“> –> return to main shop page</a>
        </div>
      </div>
    </nav>
    <div class=“container“ id=“formcontainer“>  
    
      
    <?php if($msg != “): ?> <!– alert showing part –>
        <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
      <?php endif; ?> 
       
      <br> <!– logo on the center of the page –>
      <h4>Confirmation of deletion selected category removal.</h4>
      <br>

 

      <br> <!– logo on the center of the page –>
        <img id=“calcimage“ src=“./images/delicon.png“ alt=“Calc image“ width=“150″ height=“150″>
      <br>

 

       
            
      <?php // code for GET info about what to remove and submit removing approval

 

        if(isset($_GET[subcategory_id‚]) && isset($_GET[‚category‚])  ){
            // take a data from GET link generated by adminscript
            $subcategory_id = htmlspecialchars($_GET[‚subcategory_id‘]);
            $category = htmlspecialchars($_GET[‚category‘]);
            $subcategory = htmlspecialchars($_GET[‚subcategory‘]);
           

 

        } else if (isset($_POST[‚subcategory_id‘]) && isset($_POST[‚category‘]) && isset($_POST[‚subcategory‘])) { //grab score from POST – different behavior for removal
            $subcategory_id = htmlspecialchars($_POST[‚subcategory_id‘]);
            $category = htmlspecialchars($_POST[‚category‘]);
            $subcategory = htmlspecialchars($_POST[‚subcategory‘]);

 

        }  else  { //error info message
            echo ‚<p class=“alert alert-danger“> Please specify any category for removal. </p>‘;

 

        };

 

        if(isset($_POST[‚submit‚])){
             
            if($_POST[‚confirm‚] == ‚Yes‚ ){ // delete appropriate score post with imagescreenshot
              //delete the screenshotimage from the 
              $subcategory_id = htmlspecialchars($_POST[‚subcategory_id‘]);
              $category  = htmlspecialchars($_POST[‚category ‚]);
              $subcategory = htmlspecialchars($_POST[‚subcategory‘]);
              

 

              // conect to the database
              $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);

 

              //Delete score data from the database
              $sql = „DELETE FROM bazaar_category WHERE subcategory_id = $subcategory_id LIMIT 1″;
              // execute SQL
              mysqli_query($dbc, $sql);

 

              // close database connection
              mysqli_close($dbc);

 

              // confirm executed command
              echo ‚<p> The category <strong>‘ . $category . ‚</strong> with id <strong>‘ . $subcategory_id . ‚</strong> was succesfully removed. </p>‘;

 

           
            } else {
                echo  ‚<p class=“alert alert-danger“ > The selected category was not removed. </p>‘; 
            }
        } else if (isset($subcategory_id) && isset($category)  ) {
            echo ‚<h5>Are you sure to delete the next category item from bazaar? </h5>‘; 
            // show short describtion of score for deletion
            echo ‚<p> <strong> subcategory_id: </strong> ‚ . $subcategory_id .  ‚<br> <strong> Category: </strong>‘ . $category .
                 ‚<br> <strong> Subcategory: </strong>‘ . $subcategory .  
                 ‚</p>‘; 
              
            //generating removing confirmation form      
            

 

            echo ‚<form method=“POST“ action=“removecategory.php“>‚;   //not self but direct this script removecategory.php – we dont want include any GET data tahat previously send
            echo ‚<input type=“radio“ name=“confirm“ value=“Yes“ /> Yes   ‚; 
            echo ‚<input type=“radio“ name=“confirm“ value=“No“ checked=“checked“ /> No <br><br>‘;  
            
            echo ‚<input type=“hidden“ name=“subcategory_id“ value=“‚.$subcategory_id.'“  />‘; 
            echo ‚<input type=“hidden“  name=“category“ value=“‚.$category.'“  />‘;
            echo ‚<input type=“hidden“ name=“subcategory“ value=“‚.$subcategory.'“ />‘; 
            echo ‚<input type=“submit“ class=“btn btn-danger“ value=“submit“ name=“submit“ />‚; 
            echo ‚</form>‚; 
      
        };
        echo ‚<br><br>‘;
        echo  ‚<p> <a href = „managecategory.php“> &lt;&lt Back to category management page. </a></p>‘;

 

?>
    
    
    </div>
 
     <div class=“footer“> 
          <a class=“navbar-brand“ href=“https://cdesigner.eu“> Visit us on CDesigner.eu </a>
    </div>
    
      
</body>
</html>

Conclusion and other thoughts

Our code snipets create baseline for required functionality for category management. From final code was omited parts related to user login and loged users persisency. Full bazaar app code can be obtaned from github here.