6 Replies - 259 Views - Last Post: 14 December 2017 - 01:41 PM Rate Topic: -----

#1 arvidiune  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 14-December 17

Print right answer if its selected and print selected answer if wrong

Posted 14 December 2017 - 12:09 PM

I want to print if user selected right answer, if right then print " you selected right: your selected answer is :.... " if user choose not right answer then to print his selected answer and the correct answer. All questions is in database. My function checks answers but scan it without spaces and when spaces is in the choices and user selects correct answer it says its wrong. My answers code:
<?php

require_once 'templates/header.php';

$servername2 = "localhost";
$username2 = "root";
$password2 = "";
$db2 = "user_login";

$conn2 = new mysqli($servername2, $username2, $password2, $db2);
$kat = $_SESSION['kategorija'];
$sql2 = "SELECT * FROM questions where category_id=$kat";
$results = $conn2->query($sql2);

$s=0;
$count = $_SESSION['count'];
$kategorija = $_SESSION['kategorijaName'];
?>

<body>
    <div class="container" style="margin-top:100px;">
        <div class="row" style=" margin-bottom:30px;">
            <div class="col-md-12 col-sm-12 col-xs-12">
                <div class="" style="text-align: -webkit-center;
    font-size: 2em;
    letter-spacing: 2px;    
    text-transform: uppercase;
    font-family: Open Sans, sans-serif;
    font-weight: 700;
    color: #4B4B4C;">
                    <?php echo $kategorija; ?>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 col-sm-12 col-xs-12">
                <?php
 $teisingi = 0;
 foreach($results as $result){
   
        $s++;
       
        $cAnswer = $result['correctAnswer'];

        if (isset($_POST['answers'.$s.''])){
        $answers2 = $_POST['answers'.$s.''];
        }else $answers2 = NULL;
       
        echo '<div class="borderis"> '.$result['question'].'</div>';

        if ($answers2 != NULL ){
            if($answers2 == $result['answer'.$cAnswer.''] ){
                
                        echo '<div style="margin-bottom:20px; margin-top:10px; color: #40a240;
                        letter-spacing: 2px;"> Jūsų pasirinktas atsakymas yra teisingas: '; 
                        echo ''.$answers2.'</div>';
                        $teisingi++;
                        
                    }else{
                        echo '<div style="margin-top:10px;  margin-bottom:10px; color:red; letter-spacing: 2px;"> Jūsų pasirinktas atsakymas yra neteisingas: '; 
                        echo ''.$answers2.'</div>';
                        echo '<div style="margin-top:10px; margin-bottom:20px; color: #40a240;
                        letter-spacing: 2px; "> Teisingas atsakymas yra: '.$result['answer'.$cAnswer.''].'</div>';
                        
                    } 
        }else {
            echo '<div style="margin-top:10px;  margin-bottom:20px;  letter-spacing: 2px;"> Neatsakytas </div>'; 

        }
    }
    ?>
                    <div class="row" style=" padding-top: 20px; margin-bottom:40px;">
                        <div class="col-md-3 col-sm-3 col-xs-12">
                            <a href="start-quiz.php" class="btn btn-success btn-block" id="start_btn"> Grįěti į testus </a>
                        </div>
                        <div class="col-md-3 col-sm-3 col-xs-12">
                        </div>
                        <div class="col-md-6 col-sm-6 col-xs-12" style="text-transform: uppercase;
    letter-spacing: 3px !important;
    font-size:1.3em !important;
    font-weight: 600 !important;
    text-align: -webkit-center;
    border: 3px solid #4B4B4C;
   "> Jūs atsakėte teisingai
                            <?php echo $teisingi.'/'.$count ?> </div>

                    </div>

            </div>
        </div>

    </div>
</body>

<script>
</script>
<?php

    $conn2->close();?>


And there is my questions code where I print questions:


<?php

 require_once 'templates/header.php';
 ?>  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

 <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <?php

$servername2 = "localhost";
$username2 = "root";
$password2 = "";
$db2 = "user_login";

$kat = $_POST['category'];
$_SESSION['kategorija'] = $kat;


$conn2 = new mysqli($servername2, $username2, $password2, $db2);

$query2 = "SET NAMES utf8";
$stmt2 = $conn2->prepare($query2);
$stmt2->execute();

$sql2 = "SELECT * FROM questions where category_id= $kat";
$sql3 = "SELECT category_name FROM categories where id= $kat";
$result2 = $conn2->query($sql2);
$result3 = $conn2->query($sql3);
while($row2 = $result3->fetch_assoc()) {
$kategorija = $row2['category_name'];
}

$i=0;
?>

<div class="container">


<?php






if ($result2->num_rows > 0) {



    ?>

    <div class="row">
    <div class="col-md-12 col-sm-12 col-xs-12" style="margin-top: 100px;">
    <div class="" style="text-align: -webkit-center;
    font-size: 2em;
    letter-spacing: 2px;

    text-transform: uppercase;
    font-family: Open Sans, sans-serif;
    font-weight: 700;
    color: #4B4B4C;"> <?php echo $kategorija; ?>
</div></div></div>
    <form action="atsakymai.php" method="post" id="quiz" style="margin-top:100px;" >
    <?php



    while($row = $result2->fetch_assoc()) {
       $label1 = $row['answer1'];
       $label2 = $row['answer2'];
       $label3 = $row['answer3'];
       $label4 = $row['answer4'];
       $z = 1;
       while ( $z<=4 ){
        $row['answer'.$z.''] =  preg_replace('/\s+/', '', $row['answer'.$z.'']);
       
    
        $z++;
       }

        echo '<div class="row">';
        echo '<div class="col-md-12 col-sm-12 col-xs-12">';
        echo '<div class="borderis">'.$row['question'].'</div><br>';
        $i++;

       echo '<fieldset id="group" >';

        echo '<label for="'.$row['answer1'].'"><input type="radio"  id="'.$row['answer1'].'" name="answers'.$i.'" value="'.$row['answer1'].'" class="mygtukai"> <bled></bled>
        <span>'.$label1.'</span></label>'.'<br>';


        echo '<label for="'.$row['answer2'].'"><input type="radio" id="'.$row['answer2'].'"name="answers'.$i.'" value="'.$row['answer2'].'"> <bled></bled>
        <span>'.$label2.'</span></label>'.'<br>';

        echo '<label for="'.$row['answer3'].'"><input type="radio" id="'.$row['answer3'].'"name="answers'.$i.'" value="'.$row['answer3'].'"> <bled></bled>
        <span>'.$label3.'</span></label>'.'<br>';

        echo '<label style="margin-bottom:15px;" for="'.$row['answer4'].'"><input type="radio" id="'.$row['answer4'].'"name="answers'.$i.'" value="'.$row['answer4'].'"> <bled></bled>
        <span>'.$label4.'</span></label>'.'<br>';

    echo '</fieldset>';
      echo '</div></div>';



    }
} else {
    echo "0 results";
}

?>



    


    <div id="progressbar"></div>
<div id="percentage"></div>


    <input type="submit" value="Pateikti atsakymus" name="result" class="qSubmit" id="qSubmit" />


</form>


<script>

$(document).ready(function(){
    var names = {};
    $(':radio').each(function() {
        names[$(this).attr('name')] = true;
    });
    var count = 0;
    $.each(names, function() {
        count++;
    });


   		 $("#qSubmit").click(function(){
   if ($(':radio:checked').length !== count) {
    event.preventDefault();
              alert("Atsakykite į visus klausimus!");
               }

    });
});

</script>
<script>

$(document).ready(function() {
    $('#progressbar').progressbar({
        value: 0
    });

    $('[name*=answers]').click(function() {
        var totalChecked = 0;
        var totalRadioGroups = 0;
        var previousName = '';
        $.each($('[name*=answers]'), function(index, value) {
            var radioName = $(this).attr('name');
            var radioId = this.id;

            if (previousName != radioName) {
                totalRadioGroups++;
            }
            if ($('#' + radioId).is(':checked')) {
                totalChecked++;
            }
            previousName = radioName;
        });
        var percentage = (totalChecked / totalRadioGroups) * 100;
        $('#progressbar').progressbar('value', percentage);
        $('#percentage').html(percentage.toFixed(2) + "%");
    });

});


</script>




<?php
$_SESSION['count'] = $i;
$_SESSION['kategorijaName'] = $kategorija;
$conn2->close();
$stmt2->close();
?>



Is This A Good Question/Topic? 0
  • +

Replies To: Print right answer if its selected and print selected answer if wrong

#2 astonecipher  Icon User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2364
  • View blog
  • Posts: 9,494
  • Joined: 03-December 12

Re: Print right answer if its selected and print selected answer if wrong

Posted 14 December 2017 - 12:15 PM

Deprecated MySQL functions are simpler to use (not counting all the sanitizing you need to add) than PDO or MySQLi prepared statements, but far less secure. That's why they've been deprecated. If you're just learning PHP you should start with
http://www.dreaminco...duction-to-pdo/
or
http://php.net/manua...-statements.php
When dealing with old code that uses deprecated MySQL functions you should replace them if possible. If it's not possible, your experience with PDO or MySQLi will benefit you when dealing with MySQL functions.
Was This Post Helpful? 0
  • +
  • -

#3 arvidiune  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 14-December 17

Re: Print right answer if its selected and print selected answer if wrong

Posted 14 December 2017 - 12:26 PM

View Postastonecipher, on 14 December 2017 - 12:15 PM, said:

Deprecated MySQL functions are simpler to use (not counting all the sanitizing you need to add) than PDO or MySQLi prepared statements, but far less secure. That's why they've been deprecated. If you're just learning PHP you should start with
http://www.dreaminco...duction-to-pdo/
or
http://php.net/manua...-statements.php
When dealing with old code that uses deprecated MySQL functions you should replace them if possible. If it's not possible, your experience with PDO or MySQLi will benefit you when dealing with MySQL functions.


Yeah I know, but I need to fix this code and I'm very new in PHP. Is there any possibility to fix this to print answers normally? Thanks in advance.
Was This Post Helpful? 0
  • +
  • -

#4 astonecipher  Icon User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2364
  • View blog
  • Posts: 9,494
  • Joined: 03-December 12

Re: Print right answer if its selected and print selected answer if wrong

Posted 14 December 2017 - 12:26 PM

Several things,



$_POST['answers'.$s.'']
// should be

$_POST["answers{$s}"]



echo ''.$answers2.'</div>';
vs
echo $answers2.'</div>';


// should be a JOIN not two queries
$sql2 = "SELECT * FROM questions where category_id= $kat";
$sql3 = "SELECT category_name FROM categories where id= $kat";



// You can trim this, either in the query or in php, to get make this easier to read and deal with
preg_replace('/\s+/', '', $row['answer'.$z.'']);


// This says bad things about your database design
$row['answer1']
$row['answer2']
$row['answer3']
$row['answer4']



//is this how you are checking answers?
 if ($answers2 != NULL ){
     if($answers2 == $result['answer'.$cAnswer.''] ){





There is a few other issues, but resolving those will make your overall application work more performant and maintainable.
Was This Post Helpful? 0
  • +
  • -

#5 arvidiune  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 14-December 17

Re: Print right answer if its selected and print selected answer if wrong

Posted 14 December 2017 - 12:33 PM

Thank you, this is a picture of my database. I have another table categories, where I have category_id and category_name, and each question have category_id of that category that I want to print.

This post has been edited by astonecipher: 14 December 2017 - 01:34 PM
Reason for edit:: Don't need to quote the reply above yours.

Was This Post Helpful? 0
  • +
  • -

#6 arvidiune  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 14-December 17

Re: Print right answer if its selected and print selected answer if wrong

Posted 14 December 2017 - 12:41 PM

Quote

/is this how you are checking answers?
32
if ($answers2 != NULL ){
33
if($answers2 == $result['answer'.$cAnswer.''] )

Yes, im checking is answer user selected is correct. Is there any other way to to that? Would love to know.
Was This Post Helpful? 0
  • +
  • -

#7 astonecipher  Icon User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2364
  • View blog
  • Posts: 9,494
  • Joined: 03-December 12

Re: Print right answer if its selected and print selected answer if wrong

Posted 14 December 2017 - 01:41 PM

You use the id of the answer selected as the value, but, you can't do that in your design, because the answer doesn't have an ID. You are then stuck with string comparison.


example. You have a Questions table, Answers table, and a question_answer linking table. This does a few things for you,

1. you can have as many answers as you want, without requiring a structure change to the database.
2. you can easily link the correct answer to the user answer via a unique trait.
3. it allows different types of responses.

Then, when a form is submitted, you are comparing the answer_id to the correct_ans_id, and spaces are irrelevant.




Are you sure that the answer you are recording goes with the correct answer that you are comparing it to?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1