Cookies not saved from the fourth column data in mysql? - php

I'm just building a simple todo-list. I built the checkboxes, which save as cookies so when next time users can see the checkboxes checked.
A part of my code:
//this code is in a table which shows checkboxes in each row.
//tasks is the query which selects all from the database
<form action="index.php" method="POST" id="checksubmit" name="checksubmit">
<?php
$i = 1;
while ($row = mysqli_fetch_array($tasks)) { ?>
<tr>
<td class="tick"><div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="check<?php echo $row['id'];?>" name="arraycheck[]" value="<?php echo $row['id'];?>"
<?php
if ((((isset($_POST['arraycheck'])) && (in_array($row['id'], $_POST['arraycheck'])))) || (isset($_COOKIE[$row['id']]))) {
if (!isset($_COOKIE[$row['id']])) {
setcookie ($row['id'],"checked='checked'",time()+3600000);
}
}
if ((isset($_POST['button-submit'])) && (!in_array($row['id'], $_POST['arraycheck']))) {
setcookie ($row['id'],"",time()-3600);
}
echo $_COOKIE[$row['id']];
?>>
<label class="custom-control-label" for="check<?php echo $row['id'];?>"></label>
</div>
</td>
</tr>
<?php
$i++;
}
?>
The code work just fine! Checkboxes are saved by cookies.
BUT THE PROBLEM: Only the first four rows worked, from the fifth row, everything didn't worked. What a weird error!

There are some problems with your code:
The setcookie() calls won't work at all and will fail with a "headers already sent" warning. This is the main reason why your code is not working.
Your are using tr without having a table. If you have a table outside of the form I think this is not valid.
At least in the code you posted the form is not closed.
This line produces a "undefined offset" warning if the cookie is not set:
echo $_COOKIE[$row['id']];
You should also indent your code because then you can see mistakes better.
And if not already done add this to the beginning to see errors and warnings:
error_reporting(E_ALL | E_NOTICE);

The full code:
<table class="table">
<thead class="thead-dark">
<tr>
<th>STT</th>
<th>Lời nhắc</th>
<th style="width: 50px;">Xong?</th>
<th style="width: 50px;">Ảnh</th>
</tr>
</thead>
<tbody>
<form action="index.php" method="POST" id="checksubmit" name="checksubmit">
<?php $i = 1; while ($row = mysqli_fetch_array($tasks)) { ?>
<tr>
<td> <?php echo $i; ?> </td>
<td class="task"> <?php if(isset($_COOKIE[$row['id']])) {echo '<span style="color:gray;"><strike>';} echo $row['task']; if(isset($_COOKIE[$row['id']])) {echo '</strike></span>';} ?> </td>
<td class="tick"><div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="check<?php echo $row['id'];?>" name="arraycheck[]" value="<?php echo $row['id'];?>"
<?php
if((((isset($_POST['arraycheck'])) && (in_array($row['id'], $_POST['arraycheck'])))) || (isset($_COOKIE[$row['id']]))) {
if(!isset($_COOKIE[$row['id']])) {
setcookie ($row['id'],"checked='checked'",time()+3600000); }
}
if ((isset($_POST['button-submit'])) && (!in_array($row['id'], $_POST['arraycheck']))) {
setcookie ($row['id'],"",time()-3600);
}
echo $_COOKIE[$row['id']];
?>>
<label class="custom-control-label" for="check<?php echo $row['id'];?>"></label>
</div></td>
<td><?php if (!empty($row['image'])) { ?> <i class="fas fa-image"></i> <?php } ?></td>
</tr>
<?php $i++; } ?>
<tr>
<td></td>
<td></td>
<td></td>
<td><input type="submit" value="Lưu" class="btn btn-primary" name="button-submit">
</form></td>
</tr>
</tbody>
</table>

Related

PHP Array and foreach Combination calculation

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.

Cannot delete row in database using PHP

I can't seem to delete row in database by id in php
I think the the id is not passed to the $_POST['delete']
however, the popup "Your data is deleted" is displayed, but the data is not deleted.
So I'm not sure where is the error in this code.
I also try to delete the data by its id
for example: Delete book where no='4';
and the code seems to run fine because the data is deleted in the database.
<html>
<script>
function confirmDelete() {
return confirm('Are you sure?');
}
</script>
<!DOCTYPE html>
<head>
<form action="test.php" method="POST">
<br><br><br>
<table bordercolor="#FFCC66" align="center" bgcolor="#FFFFFF">
<tr>
<th>No</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Donor's Name</th>
<th>Call Number</th>
<th>Date Received</th>
<th>Handled By</th>
<th></th>
<th></th>
</tr>
<?php
include ('config.php');
$view=mysqli_query($conn,"SELECT * FROM book");
?>
<?php while($v=mysqli_fetch_array($view)){ ?>
<tr>
<td>
<?php echo $v["no"];?>
</td>
<td>
<?php echo $v["title"];?>
</td>
<td>
<?php echo $v["author"];?>
</td>
<td>
<?php echo $v["year"];?>
</td>
<td>
<?php echo $v["donorname"];?>
</td>
<td>
<?php echo $v["callnum"];?>
</td>
<td>
<?php echo $v["datereceived"];?>
</td>
<td>
<?php echo $v["handledby"];?>
</td>
<td><input type="submit" name="delete" value="Delete" onclick="return confirmDelete('Are you sure?');" /></td>
</tr>
<?php
} ?>
</tr>
</table>
<br><br>
</form>
</body>
</html>
<?php
if(isset($_POST['delete']))
{
include('config.php');
$no =$v["no"];
$d=mysqli_query($conn,"DELETE FROM `book` WHERE no='$no'");
if ($d)
{
echo "<script type='text/javascript'> alert('Your data is deleted!'); </script>";
echo"<meta http-equiv='Refresh' content='0' >";
}
else
{
echo "<script type='text/javascript'> alert('Your data cannot delete!'); </script>";
}
mysqli_close($conn);
}
?>
Change the submit element to
<td>
<input type="submit" name="delete" value="<?php echo $v['no'];?>" onclick="return confirmDelete('Are you sure?');" />
</td>
and
$no = $_POST["delete"];
Another solution si to add a hidden input with your value.
<td>
<?php echo $v["no"];?>
<input type="hidden" value="<?php echo $v["no"];?>" />
</td>
In your php you will find the value in $_POST['no']
This solution is better to pass multiple arguments in POST like a captcha or a confirmation (checkbox).
logic is not correct, while you press the delete button, all the data will be passed along with submitting because your tag is outside of the loop.
As my opinion, you should use ajax like functionality here, or follow this method.
<?php while($v=mysqli_fetch_array($view)){ ?>
<form action="test.php" method="POST">
<tr>
<td>
<?php echo $v["no"];?>
<input type="hidden" value="<?php echo $v["no"];?>" name="no" >
</td>
<td><input type="submit" name="delete" value="Delete" onclick="return confirmDelete('Are you sure?');" /></td>
</tr>
</form>
<?php } ?>
and in your post call use $no = $_POST['no']; instead of $no =$v["no"];

Need to Insert Multiple Data by selecting Checkboxes

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
}

Post data that contains paths with ../../ gives empty $_POST array

Recently I moved my codeigniter website to a new server (goddady). Before this everything was working great with no problems. But now I started to get strange problems with post data, whenever I try to insert data that contains relative paths with dots (../../) and try to submit the form, I get an empty $_POST array. The strange thing is that this happens only with certain forms, not all of them. What could cause such problem?
Here is the form that causes problem:
<?php
if(isset($posts2) && count($posts2) == 1){
$posts2 = $posts2[0];
echo form_open_multipart('professors/update_biography/', array("id" => "professors_edit"));
echo form_hidden('posts2[id]', $posts2->id);
if(isset($user) && count($user) == 1){
$user = $user[0];
echo form_hidden('user[id]', $user->id);
echo form_hidden('user[role]', "Professor");
}
?>
<table class="admin_table">
<tr>
<th>
Биографија
</th>
<td>
<textarea name='posts2[biography]'><?php echo $posts2->biography; ?></textarea>
</td>
</tr>
<tr>
<th>
Биографија EN
</th>
<td>
<textarea name='posts2[biography_en]'><?php echo $posts2->biography_en; ?></textarea>
</td>
</tr>
<tr>
<th>
Cv
</th>
<td>
<p class="old">CV</p>
<input type="file" name='cv' id="pdf"></input>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type='submit' name='submit' value='Зачувај' />
</td>
</tr>
</table>
<?php
echo form_close();
?>
<div class="redButton" style="float:left; width: 150px;">
<?php
if(!isset($prof[0]->id)){ //da ne go prikazuva za profesor
echo anchor('professors/', 'Назад до професори');
}
?>
</div>
<?php
}
?>

Pass back values to form to populate it? (lots of values)

I need to pass back a large string of results to a form, so that the form can read those results from the URL and then populate the form with them. Problem is, the link ends up being:
&key=value&key=value ... until it can't process anymore (I assume a URL has a length limit?) resulting in my form not being able to fully populate. I need another way to pass values back to my form file.
VIEW.php file (basically just a table of values right as they are from the database, with the first column "id" being a link. When I click on "id", it goes back to my add.php(form page) and populates the form with the data matching that id)
<table border="0" cellpadding="0" cellspacing="0" id="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>MANUFACTURER</th>
<th>MODEL</th>
<th>DESCRIPTION</th>
<th>ON HAND</th>
<th>REORDER</th>
<th>COST</th>
<th>PRICE</th>
<th>SALE</th>
<th>DISCOUNT</th>
<th>DELETED</th>
<th></th>
</tr>
</thead>
<tbody>
<?php } ?>
<?php
// loop to fetch data
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>
<a href='molszewski1_a2_add.php'>$row[id]</a></td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td>$row[deleted]</td>";
$status = "$row[deleted]";
echo "<td><a href='molszewski1_a2_delete.php?id=$row[id]&flag=$status&sort=$sort'>";
$status = "$row[deleted]";
if ($status == 'n') {
$flag = "restore";
echo "delete";
} else if ( $status == 'y') {
$flag = "delete";
echo "restore";
}
echo "</a></td>";
echo "</tr>";
} ?>
<?php { ?>
</tbody>
</table>
ADD.php (form page where the form is supposed to fetch the data and populate it)
<?php
// If no form has been submitted, present form
if (empty($_GET))
{
add_form();
}
// if a form has been submitted
else
{
// if form_validity() == 1, proceed to connect
if (form_validity() == 1)
{
// connect to mysql + database
connect();
$saleItem = "n";
$discountItem = "n";
if( array_key_exists( 'saleItem', $_GET ) && $_GET['saleItem'] == 'y' )
{ $saleItem = "y"; }
if( array_key_exists( 'discountItem', $_GET ) && $_GET['discountItem'] == 'y' )
{ $discountItem = "y"; }
// get values from form, insert into database
$sql=("INSERT INTO inventory (name,
manufac,
model,
descrip,
onhand,
reorder,
cost,
price,
sale,
discont,
deleted)
VALUES ('$_GET[itemName]',
'$_GET[manufacturer]',
'$_GET[model]',
'$_GET[description]',
'$_GET[numberOnHand]',
'$_GET[reorderLevel]',
'$_GET[cost]',
'$_GET[sellingPrice]',
'$saleItem',
'$discountItem', 'n')");
// if the query doesn't work, display error message
if (!(mysql_query($sql))) { die ("could not query: " . mysql_error()); }
add_form();
// redirect to view.php after form submission
// use php instead
echo "<meta http-equiv='REFRESH' content='0;url=molszewski1_a2_view.php'>";
}
else
{
// if form is not valid (form_validity returns 0), display error messages
add_form();
}
}
?>
FUNCTIONS.php (all my functions for stuff like the form)
<?php function page_navigation(){ ?>
<div class="center">
<input type="button" value="ADD" />
<input type="button" value="VIEW" />
<input type="button" value="VIEW DELETED" />
<input type="button" value="VIEW ACTIVE" />
<br />
<br />
</div>
<?php } ?>
<?php function add_form() { ?>
<form action="molszewski1_a2_add.php" method="get" id="form">
<table width="529px">
<tr>
<td>ITEM NAME</td>
<td><input name="itemName" size="30" type="text" value="<?php echo $_GET["itemName"] ?>"/></td>
</tr>
<tr>
<td>MANUFACTURER</td>
<td><input name="manufacturer" size="30" type="text" value="<?php echo $_GET["manufacturer"] ?>"/></td>
</tr>
<tr>
<td>MODEL</td>
<td><input name="model" size="30" type="text" value="<?php echo $_GET["model"] ?>"/></td>
</tr>
<tr>
<td>DESCRIPTION</td>
<td><textarea name="description" rows="3" cols="20"><?php echo $_GET["description"] ?></textarea></td>
</tr>
<tr>
<td>ON HAND</td>
<td><input name="numberOnHand" size="30" type="text" value="<?php echo $_GET["numberOnHand"] ?>"/></td>
</tr>
<tr>
<td>REORDER LEVEL</td>
<td><input name="reorderLevel" size="30" type="text" value="<?php echo $_GET["reorderLevel"] ?>"/></td>
</tr>
<tr>
<td>COST</td>
<td><input name="cost" size="30" type="text" value="<?php echo $_GET["cost"] ?>"/></td>
</tr>
<tr>
<td>SELLING PRICE</td>
<td><input name="sellingPrice" size="30" type="text" value="<?php echo $_GET["sellingPrice"] ?>"/></td>
</tr>
<tr>
<td>SALE ITEM</td>
<td>
<input type="checkbox" name="saleItem" value="y" <?php if( isset( $_GET['saleItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td>DISCOUNTED ITEM</td>
<td>
<input type="checkbox" name="discountItem" value="y" <?php if( isset( $_GET['discountItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="save" name="submit" id="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Use method="post" and $_POST (instead of $_GET).
POST requests can be much larger than GET requests as GET requests are limited by the maximum length of a URL. POST requests are limited by the size of the max_post_size ini-value which is usually a few megabytes.

Categories