In a quiz app, I am taking user answer using a form. I am retrieving correct answer from database table. I want to compare the correct answer with the user's answer and count how many answer was right and how many answer was wrong.
Here is my form:
<form id="question" class="" action="quiz_ans.php" method="post">
<table id="quiz-question" align="center" class="row-border compact order-column stripe">
<input class="form-control" type="hidden" name="NumberofQuestions" id="NumberofQuestions" value="<?php echo $NumberofQuestions; ?>">
<thead>
<?php
if($QuizQuestions) {
$i=1;
foreach($QuizQuestions as $row):
?>
<tr>
<th><?php echo $i; ?>. <?php echo $row->Question; ?>
<br>
<?php if(isset($row->Screenshot)) { ?>
<img src="<?php echo htmlspecialchars($row->Screenshot); ?>" alt="test" height="300" width="980">
<?php } ?>
</th>
</tr>
</thead>
<tbody>
<?php if(isset($row->Option1)) { ?>
<tr class="info">
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="0"><?php echo $row->Option1; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option2)) { ?>
<tr class="info">
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="1"> <?php echo $row->Option2; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option3)) { ?>
<tr>
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="2"> <?php echo $row->Option3; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option4)) { ?>
<tr>
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="3"><?php echo $row->Option4; ?></td>
</tr>
<?php } ?>
<tr>
<td><label for="AnswerReason">Why?</label><input class="form-control" type="text" name="AnswerReason[]" id="AnswerReason" value=""></td>
</tr>
<?php if(isset($row->Id)) { ?>
<tr>
<td><input class="form-control" type="hidden" name="QuestionId[]" id="QuestionId" value="<?php echo $row->Id; ?>"></td>
</tr>
<?php } ?>
</tbody>
<?php
$i++;
endforeach;
}
?>
</table>
<br>
<input type="submit" name="submit" value="Submit" class="btn btn-success">
</form>
I am getting the user answer from the form submit:
$NumberofQuestions = $_POST['NumberofQuestions'];
$ans = implode("", $_POST['AnswerId']);
I am retreiving the correct answer from the database table:
try {
$sql = "CALL spQuizAnswers(:quiz_num)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':quiz_num', $quiz_num, PDO::PARAM_STR, 50);
$stmt->execute();
$QuizAns=$stmt->fetchAll();
$stmt->closeCursor();
} catch (PDOException $e) {
die("Error occurred:" . $e->getMessage());
}
I am comparing the user's answer and the correct answer:
for ($i=0; $i<$NumberofQuestions; $i++) {
if($QuizAns) {
foreach($QuizAns as $row):
if($row->CorrectAns == $ans[$i]){
$right++;
} elseif($ans[$i] == 4){
$not_answered++;
} else {
$wrong++;
}
endforeach;
}
}
$CorrectAnswer = $right;
$WrongAnswer = $wrong;
$NotAnswered = $not_answered;
$TotalQuestion = $right+$wrong+$not_answered;
It does not give correct calculation. For 5 questions it gives $TotalQuestion=25.
How can I achieve the correct calculation? Any help would be much appreciated.
Related
So I have a list of items and for each item, there is a remove and update button, the remove will remove the row from the database, and the update button will change the quantity.
But the problem is, I can only update or remove the last item in the list. and I have tried many things but with no solution.
Any suggestions?
The sql query and the form:
$totaloftotal=0;
try{
require('connection.php');
$sql="select i.item_name, c.qty, i.item_price, c.iid, i.item_photo, i.item_qty, c.cart_id FROM items i, cart c WHERE i.item_id=c.iid and uid=23 ";
$rs=$db->query($sql);
if($rs->rowCount()==0){
echo"CART EMPTY!!";
} else{
?>
<thead>
<tr>
<th>Update</th>
<th>Remove</th>
<th>Image</th>
<th>Product Name</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<?php
while($row = $rs->fetch()){
$total=0;
$total+=$row[2];
?>
<form method="post" action="updatecart.php">
<td><button class="btn" type="submit" name="update" >Update</button></td>
<td><button class="btn" type="submit" name="remove" >Remove</button></td>
<?php echo"$row[1]"?>
<input type="hidden" name="itemid" value=<?php echo"$row[3]"?>>
<input type="hidden" name="cartid" value=<?php echo"$row[6]"?>>
<td>
<a href="product_detail.html">
<img alt="" src="photos/<?php echo"$row[4]"?> " width= 100 height=100>
</a>
</td>
<td><?php echo"$row[0]"?></td>
<td>
<input type="number" id="quantity" name="quantity" min=1 max=<?php echo"$row[5]"?> value=<?php echo"$row[1]"?>></td> td>
<?php echo"$row[2]"?><</td>
<?php $total = $total * $row[1]?>
<td><?php echo"$total"?></td>
</tr>
<?php $totaloftotal+=$total;?>
<?php
}
//echo"$totaloftotal";
}
} catch ( PDOException $e ){
die($e->getMessage() );
}
?>
and here is the updatecart.php which is supposed to make the changes:
<?php
print_r($_POST);
extract($_POST);
if(isset($update)){
try{
require('connection.php');
$qty= $_POST["quantity"];
$itemid= $_POST["itemid"];
$cartid= $_POST["cartid"];
$qty= intval($qty);
$sql2= "update cart set qty=$qty where iid=$itemid and uid=23";
$x = $db->exec($sql2);
$db=null;
header("location:cart.php");
}catch (PDOException $e){
die( $e->getMessage() );
}
}
else{
try{
require('connection.php');
$sql2= "delete from cart where iid=$itemid";
$x = $db->exec($sql2);
$db=null;
header("location:cart.php");
}catch ( PDOException $e ){
die($e->getMessage());
}
}
?>
try use while : and endwhile
...
<tbody>
<tr>
<?php
while($row = $rs->fetch()):
?>
<?php
$total=0;
$total+=$row[2];
?>
<form method="post" action="updatecart.php">
<td> <button class="btn" type="submit" name="update" >Update</button></td>
<td> <button class="btn" type="submit" name="remove" >Remove</button></td>
<?php echo"$row[1]"?>
<input type="hidden" name="itemid" value="<?php echo $row[3]?>">
<input type="hidden" name="cartid" value="<?php echo $row[6]?>">
<td><img alt="" src="photos/<?php echo"$row[4]"?> " width= 100 height=100></td> <td><?php echo"$row[0]"?>
</td>
<td><input type="number" id="quantity" name="quantity" min=1 max=<?php echo"$row[5]"?> value=<?php echo"$row[1]"?>></td> td><?php echo"$row[2]"?><</td>
<?php $total = $total * $row[1]?> <td><?php echo"$total"?></td>
</tr>
<?php $totaloftotal+=$total;?>
<?php endwhile ?>
//echo"$totaloftotal";
.....
//Deleting is working. However, I can't delete the specified row in the table. It always deletes the last row. I hope you could help me. Thank you! This is my code for displaying data from database:
<form action="deleteCart.php" method = "post" role="form">
<?php
while ($row = mysqli_fetch_array($result2)) {
?>
<tr style="text-align: center;">
<td> <img src="images/<?php echo $row["ImageProduct1"]; ?>"/>
<td><?php echo $row['NameProduct1']; ?> </td>
<td>#<?php echo $row['OrderID']; ?></td>
<td><?php echo $row['OrderQuantity']; ?></td>
<td><input type="submit" name="cancelOrder" value = "Cancel" ></td>
<td><input type="hidden" name="hiddenID" value="<?php echo $row['OrderID']; ?>"></td>
</tr>
<?php
}
?>
</form>
//This is my code for deleting:
if(isset($_POST['cancelOrder'])){
orderID = $_POST['hiddenID'];
mysqli_query($con, "DELETE FROM OrderTable WHERE OrderID=$_POST[hiddenID];");
header('location: deleteCart.php');
}
Delete only the last record because you submitting form whole table record. you should try this code. it will work fine.
this will submit separate record.
<?php
while ($row = mysqli_fetch_array($result2)) {
?>
<form action="deleteCart.php" method = "post" role="form">
<tr style="text-align: center;">
<td><img src="images/<?php echo $row["ImageProduct1"]; ?>"/>
<td><?php echo $row['NameProduct1']; ?> </td>
<td>#<?php echo $row['OrderID']; ?></td>
<td><?php echo $row['OrderQuantity']; ?></td>
<td>
<input type="hidden" name="hiddenID" value="<?php echo $row['OrderID']; ?>">
<input type="submit" name="cancelOrder" value = "Cancel" >
</td>
</tr>
</form>
<?php
}
?>
I need to Insert data to the DB using the form given below
<form action="OtherEventPayment.php" id="frmSignIn" method="post">
<input type="hidden" name="online_id" value="<?php echo $lid; ?>" >
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Item</th>
<th>No. of Participants</th>
<th>Tick the Items</th>
</tr>
</thead>
<tbody>
<tbody>
<?php
$sn ="1";
$id = $oth_event_id;
$stmt1 = $DB_con->prepare('SELECT * FROM oth_events_details
LEFT JOIN oth_event_category ON (oth_events_details.oth_evcat_id=oth_event_category.oth_evcat_id)
WHERE oth_event_id =:uid ORDER BY oth_event_det_id DESC');
$stmt1->execute(array(':uid'=>$id));
$stmt1->execute();
if($stmt1->rowCount() > 0)
{
while($row1=$stmt1->fetch(PDO::FETCH_ASSOC))
{
extract($row1);
?>
<tr>
<td><?php echo $sn; ?></td>
<td>
<?php echo $row1['oth_category'];?> -
<?php
$group =$row1['oth_catgroup_type'];
if ($group=="S")
{
echo "Single";
}
elseif ($group=="D")
{
echo "Doubles";
}
else{
echo "Group";
}
?>
</td>
<td><?php echo $row1['participntno']; ?></td>
<td>
<b>
</b>
<input type="checkbox" name="chk[<?php echo $row1['oth_event_det_id'];?>]" value="<?php echo $row1['oth_event_det_id'];?>" id="chk[<?php echo $row1['oth_event_det_id'];?>]" />
Fees:- <?php echo $row1['oth_ev_fee'];?>
</td>
</tr>
<?php $sn++; ?>
<?php
}
}
else
{
?>
<div class="col-xs-12">
<div class="alert alert-warning">
<span class="glyphicon glyphicon-info-sign"></span> No Data Found ...
</div>
</div>
<?php
}
?>
</tbody>
</table>
<div class="col-md-6">
<input type="submit" name="selectItems" value="Submit & Proceed" class="btn btn-primary pull-right mb-xl" data-loading-text="Loading...">
</div>
</div>
<?php echo $sn1=$sn-1; ?>
</form>
in the OtherEventPayment.php i have written the code. But not working . How to Insert data correctly to DB
<?php
require_once 'dbconfig.php';
if(isset($_POST['selectItems']))
{
echo array[] = $_POST['chk[]'];
echo $oth_online_id= $_POST['online_id'];
if($oth_event_detid != ""){
for($i=0;$i<sizeof($oth_event_detid);$i++)
{
// oth_event_det_id,oth_online_id
$stmt = $DB_con->prepare('INSERT INTO othevents_itemsonline(oth_event_det_id,oth_online_id) VALUES( :oth_event_det_id, :oth_online_id)');
$stmt->bindParam(':oth_event_det_id',$oth_event_det_id);
$stmt->bindParam(':oth_online_id',$oth_online_id);
if($stmt->execute())
{
$lastonlineid= $DB_con->lastInsertId();
$successMSG = "Thank you For Registering with us . Please select the items to be participating...";
// header("refresh:0;OtherEventsOnlineRegistrationThankyou.php"); /
}
else
{
$errMSG = "error while registering....";
} } }
}
?>
Name should be same for input field. Use following code:
<input type="checkbox" name="chk[]" value="<?php echo $row1['oth_event_det_id'];?>" id="chk[<?php echo $row1['oth_event_det_id'];?>]" />
Fees:- <?php echo $row1['oth_ev_fee'];?>
You can see name. Hopefully it will be clear enough
Just change the value of you checkboxes and the value it represents but keep the name same with the others, yet it should have a name with []
<input type="checkbox" id="chk<?php echo $row1['oth_event_det_id'];?>" name="chk[]" value="<?php echo $row1['oth_event_det_id'];?>">
<label for="chk<?php echo $row1['oth_event_det_id'];?>"><?php echo $row1['oth_event_det_id'];?></label>
having a name chk[] like this will send and serve as an array in your get or post-function so loop it on controller or function that will add it in the DB
upon inserting it,
$data = $_GET['chk']; //this is in array form
foreach($data as $chk){
//insert code here
}
I can't do the live search table thing. Can someone help me please?
Here is my code. I want to show only the data I've search.........................................................................................................................................................................................................................................................................
<?php
//include the connection file
include "conn.php";
$sql = "SELECT * FROM tblreservation";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= "WHERE Name = '{search_term}'";
}
$query = mysql_query($sql) or die(mysql_error());
?>
<form name="search_form" method="POST" action="trys.php" align="center">
Search: <input type="text" name="search_box" value="" />
<input type="submit" name="search" value="Search the table...">
</form>
<table width="70%" cellpadding="5" cellspace="5">
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Packages</td>
<td><select name="Packages" class="fieldsize">
<option value="">select package</option>
<option value="budget" <?php if($valid_Packages=='budget') echo "selected='selected'";?>>Budget</option>
<option value="standard" <?php if($valid_Packages=='standard') echo "selected='selected'";?>>Standard</option>
<option value="super" <?php if($valid_Packages=='super') echo "selected='selected'";?>>Super</option>
<option value="mega" <?php if($valid_Packages=='mega') echo "selected='selected'";?>>Mega</option>
</select>
<span class="err"><?php echo $error["Packages"];?></span></td>
</tr>
<td>Contactno</td>
<td>Gender</td>
<td><input type="radio" name="gender" value="male" <?php if($valid_gender=='male') echo "checked='checked'";?> />
Male
<input type="radio" name="gender" value="female" <?php if($valid_gender=='female') echo "checked='checked'";?>/>
Female <span class="err"><?php echo $error["gender"];?></span></td>
<td>file</td>
<td><input type="file" name="file" value="upload" />
<span class="err"><?php echo $error["file"];?></span></td>
<td>Address</td>
</tr>
<?php while ($row = mysql_fetch_array($query)) { ?>
<td><?php echo $row['id']; ?> </td>
<td><?php echo $row['Name']; ?> </td>
<td><?php echo $row['Email']; ?> </td>
<td><?php echo $row['Packages']; ?> </td>
<td><?php echo $row['Contactno']; ?> </td>
<td><?php echo $row['Gender']; ?> </td>
<td><?php echo $row['file']; ?> </td>
<td><?php echo $row['Address']; ?> </td>
</tr>
<?php } ?>
</table>
You are missing a $ and a space in this line:
$sql .= "WHERE Name = '{search_term}'";
The correct line should be as follows:
$sql .= " WHERE Name = '{$search_term}' ";
The SQL statement you are currently generating is exactly this:
SELECT * FROM tblreservationWHERE Name = '{search_term}'
Additionally, I would recommend checking for the existence of $_POST['search_box'] rather than $_POST['search'] in your if-statement and that it actually has a value before appending it as this is what you actually want to use in your query:
if (isset($_POST['search_box']) && $_POST['search_box']) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= " WHERE Name = '{$search_term}' ";
}
I have problem with bindings, I want to insert name or surname in label Pisatelj as keyword to search for this author,
I want also do the same way if I insert keyword for Naslov(=Title of book)
please correct my code
I have this code in php with postgres:
function get_knjige_sql ( )
{
global $CRUD;
$dbh = $CRUD['dbh'];
$str_query = '';
if(isset($_POST['Knaslov'])){
$str_query = addslashes($_POST['Knaslov']);
}
if(isset($_POST['Ppriimek'])){
$str_query = addslashes($_POST['Ppriimek']);
}
$query = " SELECT * FROM knjiga, pisatelj, zaloga WHERE (knjiga.naslov ILIKE '?' OR CONCAT(pisatelj.ime, ' ', pisatelj.priimek) ILIKE '?' ) AND knjiga.p_id = pisatelj.p_id AND knjiga.k_id = zaloga.k_id AND zaloga.prodana = false ";
if($sth)
$sth->bindValue(':Knaslov', $Knaslov, PDO::PARAM_STR);
$sth->bindValue(':Ppriimek', $Ppriimek, PDO::PARAM_STR);
if($sth)
$sth->execute();
else error('get_knjige_sql: select prepare returned no statement handle');
$err = $sth->errorInfo();
if($err[0] != 0) error( $err[2] );
return($sth);
}
main.php:
<!-- main html file for CRUD (php version) -->
<?php echo $CRUD["MESSAGES"] ?><?php echo $CRUD["ERRORS"] ?>
<div class="form">
<form action="<?php echo $CRUD["SELF"] ?>" method="post" name="knjiga">
<p class="subheading"><?php echo $CRUD["FORM_HEAD"] ?></p>
<table class="form">
<tr>
<td><p class="Afield"> Naslov:</p></td>
<td><input class="Afield" type="text" name="Knaslov" value="<?php echo $CRUD["Knaslov"] ?>"> </td>
</tr>
<tr>
<td><p class="Afield"> Isbn:</p></td>
<td><input class="Afield" type="text" name="kisbn" value="<?php echo $CRUD["Kisbn"] ?>"> </td>
</tr>
<tr>
<td><p class="Afield"> Cena:</p></td>
<td><input class="Afield" type="text" name="Kcena" value="<?php echo $CRUD["Kcena"] ?>"> </td>
</tr>
<tr>
<td><p class="Afield"> Pisatelj:</p></td>
<td><input class="Afield" type="text" name="Ppriimek" value="<?php echo $CRUD["Pime"] ?><?php echo $CRUD["Ppriimek"] ?>"> </td>
</tr>
<tr class="buttons"><td colspan="2">
<p class="buttons">
<?php echo $CRUD["BUTTONS"] ?><?php echo $CRUD["HIDDENS"] ?>
</p>
</td></tr>
</table>
</form>
</div>
<?php echo $CRUD["PRECONTENT"] ?><?php echo $CRUD["CONTENT"] ?><?php echo $CRUD["POSTCONTENT"] ?>