Bazaar – php example code – part 4 – Selling item script

Our special Christmass article focus on listening item for sell on bazaar page. Data are obtained from registered user, inserted into a database and because default published filed in bazaar_item table is false, waiting for admin approval. In final version, this page is available only for registered user.

Expectation from sellingitem script

In final applicaton, selling page is available only for common registered user. User must be able do these things:

  • decribe name and price for selling item
  • add up to three different photos
  • select category with subcategory
  • provide any further describtion for selling item
  • item is not listed for sell untip approval of admin of the page

After sucessful post for sell, short describtion about adding document to a database is generated in pottom part of form.

After finalizing other main parts of app responsible for user management, we will add column for marking selling by users_id for difrerentiating of the seller. When someone decide to buy any their item, seller must be notified about buy and must fullfil item delivery.

Visual look of the page

Sell item page consist from sell form and list of published item for sell. In the middle part, ist optionaly after succesfull post displayed short info about user action.

Implementation of functionality

Main part of page consist form form part. In this part is insered script for generating available category list obtained from bazaar_category table.

Separate par enable selecting up to three files fortransfer. First screenshot of product is required and can not be ommited. Other two are optional as you can see. Separate Javascript code is responsible for listening file path after selecting them into a dialog field.

Next output show contetnt of the form:

<form enctype=multipart/form-data“ method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“> // because data file transfer enctype must be defined in form tag!!!
      <input type=“hidden“ name=“MAX_FILE_SIZE“ value=“5242880″>
          <div class=“form-group“>
              <label>* Please provide name of selling item:</label>
              <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚name_of_item‘]) ? $name_of_item : “; ?>'“ name=“name_of_item“ class=“form-control“ value=“<?php echo isset($_POST[‚name_of_item‘]) ? $name_of_item : ‚Name for product‘; ?>“>
              

              <label>* Please provide price for item in €:</label>
              <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚price_eur‘]) ? $price_eur : “; ?>'“ name=“price_eur“ class=“form-control“ value=“<?php echo isset($_POST[‚price_eur‘]) ? $price_eur : ‚Price in €‘; ?>“>
              
              <!– slection of category and subcategory –>
              <label>* Select main category-subcategory for proper item listing on bazar pages:</label>
              <input list=“category_subcategory“ name=“category_subcategory“ >
                <datalist id=“category_subcategory“> <!– must be converted in subcategory_id in script – marked with (*) –>
                    <?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, subcategory FROM bazaar_category ORDER BY category ASC, subcategory 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‘] .“-„.$row[‚subcategory‘] . „>„;
                                            
                                            
                                    
                                    }
                                    
                                    // 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>
                <p> If no proper category-subcategory exist, please contact admin of the pages for creation them for you. </p>

                <!– users_id from session obtaining – for debuging and testing is set as hidden –>
                <input type=“hidden“ name=“users_id“ value=“1″>

              
          </div>
          
          <p> In this part you can select upto 3 pictures of the product. First picture is required! </p>
          <label>* Please select location of your score screenshot from drive – max 5MB!</label>
          <div class=“custom-file“>
          
          <input type=“file“ name=“screenshot1″ class=“custom-file-input“ id=“screenshot1″ lang=“en“ onchange=“getFilename(this)“>
              <label class=“custom-file-label1 custom-file-label“  for=“customFile“>Screenshot1 – required:</label>

            
             
          </div>     

          <div class=“custom-file“>
          <input type=“file“ name=“screenshot2″ class=“custom-file-input“ id=“screenshot2″ lang=“en“ >
              <label class=“custom-file-label2 custom-file-label“ for=“customFile“>Screenshot2 – optional:</label>

             
              
             
          </div>

          <div class=“custom-file“>
          <input type=“file“ name=“screenshot3″ class=“custom-file-input“ id=“screenshot3″ lang=“en“ >
              <label class=“custom-file-label3 custom-file-label“ for=“customFile“>Screenshot3 – optional:</label>
                
                    
              </div>

              <script type=“application/javascript“> // javascript handling chaging filename of selected file
               $(document).ready(function(){
                $(„#screenshot1“).change(function(){
                    //alert(„A file 1 has been selected.“);
                    var thefile1 = document.getElementById(‚screenshot1‘);
                    
                    var fileName1 = thefile1.value;
                    //var fileName1 = „A file 1 has been selected.“;
                    $(‚.custom-file-label1‘).html(fileName1);
                    
                });
                $(„#screenshot2“).change(function(){
                    //alert(„A file 2 has been selected.“);
                    var thefile2 = document.getElementById(‚screenshot2‘);
                    
                    var fileName2 = thefile2.value;
                    //var fileName2 = „A file 2 has been selected.“;
                    $(‚.custom-file-label2‘).html(fileName2);
                });
                $(„#screenshot3“).change(function(){
                    //alert(„A file 3 has been selected.“);
                    var thefile3 = document.getElementById(‚screenshot3‘);
                    
                    var fileName3 = thefile3.value;
                    //var fileName3 = „A file 3 has been selected.“;
                    $(‚.custom-file-label3‘).html(fileName3);
                });
              });
            
              
               
             </script>
            
           

          <br><br>
         
          
          <div class=“form-group“>
            <label>* Item description:</label>  <!– textera for input large text –>
            <textarea id=“item_description“ onfocus=“this.value='<?php echo isset($_POST[‚item_descriptio‘]) ? $item_description : ‚Please provide description of selling item …‘; ?>'“ name=“item_description“ class=“form-control“ rows=“3″ cols=“50″><?php echo isset($_POST[‚item_description‘]) ? $item_description : ‚Description of item for sell goes here …‘; ?></textarea>
          </div>

          

          <!– div class=“form-group“>
            <label>Your message for Guestbook:</label–>  <!– textera for input large text –>
            <!– textarea id=“postmessage“ name=“postmessage“ class=“form-control“ rows=“6″ cols=“50″><?php echo isset($_POST[‚postmessage‘]) ? $postmessage : ‚Your text goes here …‘; ?></textarea>
          </div–>
     
          <button type=“submit“ name=“submit“ class=“btn btn-warning“> Add item for sell </button>
          <button type=“submit“ name=“reset“ class=“btn btn-info“> Reset form </button>
          
          <!– remove comment after implementation
          <button type=“submit“ name=“delete“ class=“btn btn-danger“> Delete recently posted score </button>
          –>
          <button type=“submit“ name=“reset“ class=“btn btn-info“> Reset form </button>
          <br><br>
          

          <?php   //part displaying info after succesfull added subscriber into a mailinglist
                 if ($is_result ) {
                    

                        echo „<br> <br>“;
                        echo “ <table class=\“table table-success\“> „;
                        echo “ <tr>
                               <td><h5> <em> Item for selll: </em> $name_of_item for $price_eur €  </h5> <h5> has been succesfully added to selling list. Item will be visible
                               on bazaar page after admin approval. </h5> „;
                               $image_location = IMAGE_PATH.$screenshot1;
                        echo “ <img src=\“$image_location\“ alt=\“ score image \“  height=\“150\“> „;       
                        
                          
                        echo “     <td>   </tr> „; 
                        echo “ </table> „;
                    
                    //echo “ <input type=“text“ id=“result_field“ name=“result_field“ value=“$result“  >  <br>“ ;
                } ; 
                 ?>
                 <br>
        
      </form>

Part responsible for obtaining data after hitting submit button consist from:

if(filter_has_var(INPUT_POST, ‚submit‘)) {
        // Data obtained from $_postmessage are assigned to local variables
        $name_of_item = htmlspecialchars($_POST[‚name_of_item‘]);
        $price_eur = htmlspecialchars($_POST[‚price_eur‘]);
        $users_id = htmlspecialchars($_POST[‚users_id‘]);
        //echo ‚users_id‘; echo $users_id;
        
        $category_subcategory = htmlspecialchars($_POST[‚category_subcategory‘]); // must be converted to subcategory_id (*)
            // separate category and subcategory with strtok() function 
            $words = explode(‚-‚, $category_subcategory);
            $category=$words[0];
            //echo $category;
            //echo ‚<br>‘;
            $subcategory=$words[1];
            //echo $subcategory;
        
        
        $screenshot1 = htmlspecialchars($_FILES[‚screenshot1‘][‚name‘]);
        $screenshot2 = htmlspecialchars($_FILES[‚screenshot2‘][‚name‘]);
        $screenshot3 = htmlspecialchars($_FILES[‚screenshot3‘][‚name‘]);
        $item_description = htmlspecialchars($_POST[‚item_description‘]);

        // (*) — conversion of category and subcategory into category%id
                    $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 subcategory_id FROM bazaar_category WHERE category = „.“‚$category'“. “ AND subcategory = „.“‚$subcategory'“ ;

                    // 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
                                
                                $subcategory_id = $row[‚subcategory_id‘] ;
                                    
                            }
                            
                            
                            // Free result set
                            mysqli_free_result($output);
                        } else {
                            echo „There is no souch category-subcategory in category table. Please correct your error.“; // 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);
        

        // Controll if all required fields was written
        if(!empty($name_of_item) && !empty($price_eur) && !empty($subcategory_id) && !empty($screenshot1)) { // these item identifiers are mandatory and can not be empty
            // If check passed – all needed fields are written
            // Check if E-mail is valid
            

                
                // move image to /images final folder from demporary download location
                $target1 = IMAGE_PATH . $screenshot1;
                $target2 = IMAGE_PATH . $screenshot2;
                $target3 = IMAGE_PATH . $screenshot3;

                // !!! Add entry to the database and redraw all score in chart list descending from highest score

                   // insert into databse 
                      if (move_uploaded_file($_FILES[‚screenshot1‘][‚tmp_name‘], $target1)) {
                            move_uploaded_file($_FILES[‚screenshot2‘][‚tmp_name‘], $target2);
                            move_uploaded_file($_FILES[‚screenshot3‘][‚tmp_name‘], $target3);
                            // make database connection
                            $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());
                                }
                            
                            // INSERT new entry
                        
                            $sql = „INSERT INTO bazaar_item (name_of_item, price_eur, subcategory_id, users_id, item_add_date, screenshot1, screenshot2, screenshot3, item_description) 
                            VALUES (‚$name_of_item‘, $price_eur , ‚$subcategory_id‘ , ‚$users_id‘ , now(), ‚$screenshot1‘, ‚$screenshot2‘, ‚$screenshot3‘, ‚$item_description‘ )“;
                            //show added item true
                            $is_result = true; 
                            if(mysqli_query($dbc, $sql)){
                                
                                $msg = ‚New item ‚.$name_of_item. ‚ for ‚. $price_eur. ‚ € succesfully added to sell item – waiting for admin approvall.‘;
                                $msgClass = ‚alert-success‘;
                            } else {
                                
                                $msg = „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc);
                                $msgClass = ‚alert-danger‘;
                            }

                            // end connection
                                mysqli_close($dbc);
                                
            
            
                        } else {
                            // Failed – if not all fields are fullfiled
                            $msg = ‚Please fill in all * marked contactform fields‘;
                            $msgClass = ‚alert-danger‘; // bootstrap format for allert message with red color
                        };
            };              

    };  

Conclusion and other thoughts

Our page must be updated with code displaying its content and menus diferently for loged in user or anonymous users. Next improvement is expanding/ altering code to mark added item by users_id from active session for distinguishing between submitters.

Full code of application in as is current state can be obtained for further study from here.