Benchmarkchart – php example code – part 2 – submiting score

image_pdfimage_print

Article describe part of final app responsible for submiting particular score with picture verification. Uploaded image is moved from temporary server location into a images folder.

Behavior of index.php app

Our index.php is responsible for submiting score, nickname, e-mail and verification photo. Location of the photo is stored in a database table but photo is uploaded into a server temp folder and next moved into a images folder.

Handling of display location of uploaded picture take simple javascript as follows:

<input type=“file“ name=“screenshot“ class=“custom-file-input“ id=“screenshot“ lang=“en“>
              <label class=“custom-file-label“ for=“customFile“> Screenshot:</label>
          </div>
            
             <script type=“application/javascript“> 
// javascript handling chaging filename of selected file
              $(‚input[type=“file“]‘).change(function(e){
              var fileName = e.target.files[0].name;
              $(‚.custom-file-label‘).html(fileName);
              });
             </script>

Form for obtaining score data follow

<form enctype=“multipart/form-data“ method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“>
      <input type=“hidden“ name=“MAX_FILE_SIZE“ value=“5242880″>
          <div class=“form-group“>
              <label>* Please provide Your score:</label>
              <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚score‘]) ? $score : “; ?>'“ name=“score“ class=“form-control“ value=“<?php echo isset($_POST[‚score‘]) ? $score : ‚Your becnhmark score‘; ?>“>
              

              <label>* Please provide Your nickname:</label>
              <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚nickname‘]) ? $nickname : “; ?>'“ name=“nickname“ class=“form-control“ value=“<?php echo isset($_POST[‚nickname‘]) ? $nickname : ‚Your nickname‘; ?>“>
          </div>
          <div class=“form-group“>
            <label>* E-mail:</label>
            <input type=“text“ onfocus=“this.value='<?php echo isset($_POST[‚email‘]) ? $email : ‚@‘; ?>'“name=“email“ class=“form-control“ value=“<?php echo isset($_POST[‚email‘]) ? $email : ‚@‘; ?>“>
          </div>
          
          <label>* Please select location of your score screenshot from drive – max 5MB!</label>
          <div class=“custom-file“>
          
          <input type=“file“ name=“screenshot“ class=“custom-file-input“ id=“screenshot“ lang=“en“>
              <label class=“custom-file-label“ for=“customFile“>Screenshot:</label>
          </div>
            
             <script type=“application/javascript“> // javascript handling chaging filename of selected file
              $(‚input[type=“file“]‘).change(function(e){
              var fileName = e.target.files[0].name;
              $(‚.custom-file-label‘).html(fileName);
              });
             </script>

          <br><br>

          
          <div class=“form-group“>
            <label>Optionally – Your score comment:</label>  <!– textera for input large text –>
            <textarea id=“message_from_submitter“ onfocus=“this.value='<?php echo isset($_POST[‚message_from_submitter‘]) ? $message_from_submitter : ‚Your score escribing text goes here …‘; ?>'“ name=“message_from_submitter“ class=“form-control“ rows=“3″ cols=“50″><?php echo isset($_POST[‚message_from_submitter‘]) ? $message_from_submitter : ‚Your score escribing text goes here …‘; ?></textarea>
          </div>

          <div class=“form-group“>
            <input type=“checkbox“ name=“gdpr“ class=“form-control“ value=“<?php echo isset($_POST[‚gdpr‘]) ? $gdpr : ‚gdpr‘; ?>“>
            <label>* I agree with GDPR regulations</label>

            
          </div>

         
     
          <button type=“submit“ name=“submit“ class=“btn btn-warning“> Submitt score </button>
          
          <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
          echo ‚ <button class=“btn btn-secondary btn-lg “ onclick=“location.href=\’chart.php\'“ type=“button“>  Take a look at actual chart -> </button>‘;
          ?>
          <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> E-mail: </em> $score from $nickname  </h5> <h5> has been succesfully added to becnhmark chart </h5> „;
                               $image_location = IMAGE_PATH.$screenshot;
                        echo “ <img src=\“$image_location\“ alt=\“ score image \“  height=\“150\“> „;       
                        if ($gdpr == true ) { echo „<h5> GDPR accepted </h5>“;  } ; //if GDPR rights granted
                          
                        echo “     <td>   </tr> „; 
                        echo “ </table> „;
                    
                    //echo “ <input type=“text“ id=“result_field“ name=“result_field“ value=“$result“  >  <br>“ ;
                } ; 
                 ?>
                 <br>
        
      </form>

Last part is responsible for showing uploaded data into a database.

Script responsible for inserting data into database

Next part is responsible for get data from $_POSTasociative array, inserting them into a variable and sending e-mail about succesfull post. Next inserting data into a databasetable and moving uploaded photo.

<?php
    require_once(‚appvars.php‘); // including variables for database
    // two variables for message and styling of the mesage with bootstrap
    $msg = “;
    $msgClass = “;

    // default values of auxiliary variables
    $email = „“;
    $nickname = „“;
    $screenshot = „“;
    $gdpr = false;
    $score = ‚0‘;
    $message_from_submitter = “;
    $is_result = false//before hitting submit button no result is available
    


    // Control if data was submitted
    if(filter_has_var(INPUT_POST, ‚submit‘)){
        // Data obtained from $_postmessage are assigned to local variables
        $nickname = htmlspecialchars($_POST[‚nickname‘]);
        $screenshot = htmlspecialchars($_FILES[‚screenshot‘][‚name‘]);
        $email = htmlspecialchars($_POST[‚email‘]);
        $gdpr = isset($_POST[‚gdpr‘]); // checkbox doesnot send post data, they must be checked for its set state !!!
        $score = htmlspecialchars($_POST[‚score‘]); 
        $message_from_submitter = htmlspecialchars($_POST[‚message_from_submitter‘]);
        
        

        // Controll if all required fields was written
        if(!empty($email) && !empty($nickname) && !empty($score) && !empty($screenshot) && $gdpr ){
            // If check passed – all needed fields are written
            // Check if E-mail is valid
            if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
                // E-mail is not walid
                $msg = ‚Please use a valid email‘;
                $msgClass = ‚alert-danger‘;
            } else {
                // E-mail is ok
                $is_result = true;
                $toEmail = ‚ciljak@localhost.org‘; //!!! e-mail address to send to – change for your needs!!!
                $subject = ‚New submitted score ‚.$nickname.‘ ‚.$score;
                $body = ‚<h2>To your becnhmark chart was added new score from:</h2>
                    <h4>Name</h4><p>‘.$nickname.'</p>
                    <h4>Email</h4><p>‘.$email.'</p>
                    ‚;

                // Email Headers
                $headers = „MIME-Version: 1.0″ .“\r\n“;
                $headers .=“Content-Type:text/html;charset=UTF-8″ . „\r\n“;

                // Additional Headers
                $headers .= „From: “ .$nickname. „<„.$email.“>“. „\r\n“;
                
                // move image to /images final folder from demporary download location
                $target = IMAGE_PATH . $screenshot;

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

                   // insert into databse 
                      if (move_uploaded_file($_FILES[‚screenshot‘][‚tmp_name‘], $target)) {
                        // 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
                        $date = date(‚Y-m-d H:i:s‘); // get current date to log into databse along postmessage written
                        $sql = „INSERT INTO benchmark_chart (nickname, write_date, email, GDPR_accept, screenshot, message_from_submitter, score
                        VALUES (‚$nickname‘, now() , ‚$email‘ , ‚$gdpr‘ , ‚$screenshot‘, ‚$message_from_submitter‘, ‚$score‘)“;



                        if(mysqli_query($dbc, $sql)){
                            
                            $msg = ‚New score ‚.$score. ‚ from ‚. $nickname. ‚ succesfully added to chart.‘;
                            $msgClass = ‚alert-success‘;
                        } else {
                            
                            $msg = „ERROR: Could not able to execute $sql. “ . mysqli_error($dbc);
                            $msgClass = ‚alert-danger‘;
                        }

                        // end connection
                            mysqli_close($dbc);
                      };       
                if(mail($toEmail, $subject, $body, $headers)){
                    // Email Sent
                    $msg .= ‚ Your benchmark score was sucessfully send via e-mail to page admin.‘;
                    $msgClass = ‚alert-success‘;
                } else {
                    // Failed
                    $msg = ‚ Your benchmark was not sucessfully send via e-mail to page admin.‘;
                    $msgClass = ‚alert-danger‘;
                }
            }
        } 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
        }

    };  
 
  php>

Showing submited scores in a table

Last interesting part of index.php page show resulting score in form a table. Thic code is reused from mailer app but add output for uploaded picture. Database contains name of picture. Global variable contains location of image folder where uploaded image is moved from temporary upload folder.

 <?php // code showing all subscribers in form of a table at end of the page
 
/* Attempt MySQL server connection.*/
$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 benchmark_chart ORDER BY score DESC“;  // read in reverse order of score – highest score first
/***********************************************************************/
/*        Output in Table – solution 1 – for debuging data from database           */
/***********************************************************************/
 
echo „<h4>Chart of benchmark results</h4>“;
echo „<br>“;
//echo ‚ <button class=“btn btn-secondary btn-lg “ onclick=“location.href=\’unsubscribe.php\'“ type=“button“>  Unsubscribe by e-mail -> </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>id</th>“;
                    echo „<th>score</th>„;
                    echo „<th>nickname</th>„;
                    echo „<th>date of post</th>“;
                    echo „<th>screenshot</th>„;
                    
                    
                echo „</tr>„;
            while($row mysqli_fetch_array($output)){ //next rows outputed in while loop
                echo “ <div class=\“mailinglist\“> “ ;
                echo „<tr>„;
                    echo „<td>“ . $row[‚id‘] . „</td>„;
                    echo „<td>“ . $row[‚score‘] . „</td>„;
                    echo „<td>“ . $row[‚nickname‘] . „</td>„;
                    echo „<td>“ . $row[‚write_date‘] . „</td>„;
                    $image_location = IMAGE_PATH.$row[‚screenshot‘];
                        echo „<td> <img src=\“$image_location\“ alt=\“ score image \“  height=\“95\“> <td>„; 
                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);
?>

Final code for study

Complete code for further study with database table creational script can be obtained from github here.

Share the article via the network
Translate »