Checkboxes Do Not Get Processed Even Without Pagination - php

I'm aware that with pagination, if a checkbox is clicked and you move onto another page, that checked checkbox is no longer recognized, so I made my php pull depending on a category chosen by the user, and each row spits out in a w3css w3-third div:
while($rowtbl = mysqli_fetch_array($resulttbl)) {
?>
<div id="parent">
<div class="<?php echo $rowtbl['brand']?>">
<section class="allitems">
<div class="w3-third w3-margin-bottom" id="itemsToFilter" data-type="<?php echo $rowtbl['brand']?>">
<ul class="w3-ul w3-border w3-center w3-hover-shadow" >
<li class="w3-padding-16 w3-green">Desc: <b><?php echo htmlspecialchars($rowtbl['description']) ?></b>
<input type="hidden" name="descriptionid<?php echo $i; ?>" value="<?php echo $rowtbl['description']; ?>" /></li>
<li class="w3-padding-4">Brand: <b><?php echo htmlspecialchars($rowtbl['brand']) ?></b>
<input type="hidden" name="brandid<?php echo $i; ?>" value="<?php echo $rowtbl['brand']; ?>" /></li>
<li class="w3-padding-4">Category: <b><?php echo htmlspecialchars($rowtbl['category']) ?></b>
<input type="hidden" name="categoryid<?php echo $i; ?>" value="<?php echo $rowtbl['category']; ?>" /></li>
<li class="w3-padding-4">Item#: <b><?php echo htmlspecialchars($rowtbl['itemNu']) ?></b>
<input type="hidden" name="itemid<?php echo $i; ?>" value="<?php echo $rowtbl['itemNu']; ?>" /></li>
<li class="w3-padding-2">Pack Size: <b><?php echo htmlspecialchars($rowtbl['packsz']) ?></b>
<input type="hidden" name="packszid<?php echo $i; ?>" value="<?php echo $rowtbl['packsz']; ?>" /></li>
<?php if ($rowtbl['bc'] == "Y") { ?>
<li class="w3-padding-10">Broken Cs: <b><input type="checkbox" value="checkedup" name="bcase<?php echo $i; ?>" /></b></li>
<?php }
else { ?>
<li class="w3-padding-10">Broken Cs: <b><input type="checkbox" value="notcheckedup" name="bcase<?php echo $i; ?>" disabled /></b></li>
<?
}
?>
<li><input type="checkbox" name="checkbox<?php echo $i; ?>" /></li>
<input type="hidden" name="roses" id="roses" value="<?php echo $i; ?>" />
<input type="hidden" name="filler<?php echo $i; ?>" id="filler" />
</ul>
</div>
</section>
</div>
</div>
<?php $i++; //increment counter variable
} ?>
Everything is fine in regards to adding any item(s) to the db, until I get to any div passed 142. After that, when i click add, the page refreshes as if it was processed, but nothing gets added to the db.
What am I doing wrong?
Thanks in advance!
Edit: showing the php that adds items to the db:
<?php
if(isset($_POST['submitnew'])){
for ($i=1;$i<=$_POST['roses'];$i++)
{
if(isset($_POST['checkbox'.$i]))
{
$custnum = $_SESSION['customerNumber'];
$category = $_POST['categoryid'.$i];
$brand = $_POST['brandid'.$i];
$description = $_POST['descriptionid'.$i];
$pksz = $_POST['packszid'.$i];
$itemnum = $_POST['itemid'.$i];
if($_POST['bcase'.$i] == "notcheckedup")
{
$bcc = "n";
$eaa = 0;
} elseif ($_POST['bcase'.$i] == "checkedup" && isset($_POST['bcase'.$i]))
{ $bcc = "y";
$eaa = 1;
} else
{
$bcc = "y";
$eaa = 0;
};
$ordNew = "INSERT INTO `abc123` (`CustNo`,`category`, `brand`, `description`, `pksz`, `ea`, `itemNu`, `bc`) values('$custnum', '$category', '$brand', '$description', '$pksz', '$eaa', '$itemnum', '$bcc')";
mysqli_query($link, $ordNew);
}
header("Location: index.php");
}
}
?>

Related

How to add caption field for every image preview and post all caption through one submit button

This is my code I want to add one input field for every image preview and save it to db.. the field is coming but I'm not getting any data.. can anyone suggest how can I post them???
$fetch_imgid=$con->prepare("SELECT * FROM attempt010 where link='$rand'");
$fetch_imgid->setFetchMode(PDO:: FETCH_ASSOC);
$fetch_imgid->execute();
?>
<ul class="reorder_ul reorder-photos-list" id="previewImg">
<?php
while($row = $fetch_imgid->fetch()):
$delid = $row['id'];
//echo $row['id'].' '.$row['name'].'<br/>';?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle" data-image-id="<?php echo $delid; ?>">
<img src="uploads/<?php echo $row['name']; ?>" alt="">
<input type="submit" class="del_btn" value="Delete Image" />
<input type="text" id="cap" name="cap[]" placeholder="Enter Caption Here" />
<input type="hidden" id="cap_id" value="<?php echo $row['id']; ?>" />
<?php
endWhile;
?>
</ul>
<input type="submit" value="Add Caption" name="addcap" /> <?php include('addcap.php'); ?>
and this is addcap.php
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
if(isset($_POST['addcap'])){
foreach($_POST['cap'])
{
$imgcap = $_POST['cap'];
if($imgcap!=empty())
{
try
{
$con=new PDO("mysql:host=localhost;dbname=newimg","root","");
$sql=$con->prepare("UPDATE attempt010 SET caption='$imgcap' WHERE id='$cap_id'");
$sql->execute();
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
}
}
?>
<input type="hidden" id="cap_id" value="<?php echo $row['id']; ?>" />
Must have unique id. You can't send multiple fields with same id. You will get only last one.
For example:
$fetch_imgid=$con->prepare("SELECT * FROM attempt010 where link='$rand'");
$fetch_imgid->setFetchMode(PDO:: FETCH_ASSOC);
$fetch_imgid->execute();
?>
<form action="addcap.php" method="post">
<ul class="reorder_ul reorder-photos-list" id="previewImg">
<?php
$id_array="";
while($row = $fetch_imgid->fetch()):
$id_array = $id_array.$row['id'].",";
$delid = $row['id'];
//echo $row['id'].' '.$row['name'].'<br/>';?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle" data-image-id="<?php echo $delid; ?>">
<img src="uploads/<?php echo $row['name']; ?>" alt="">
<input type="text" id="cap_<?php echo $row['id']; ?>" placeholder="Enter Caption Here" />
<?php
endWhile;
$id_array = substr($id_array, 0, -1);
?>
<input type="hidden" id="cap_ids" value="<?php echo $id_array ; ?>" />
</ul>
<input type="submit" value="Add Caption" name="addcap" />
</form>
<!--addcap.php-->
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
if(isset($_POST['addcap'])){
if(isset($_POST['cap_ids'])){
$ids_array = explode(",", $_POST['cap_ids']);
foreach($ids_array as $ids)
{
$idcap = 'cap_'.$ids;
$imgcap = $_POST[$idcap];
if($imgcap!=empty())
{
try
{
$con=new
PDO("mysql:host=localhost;dbname=newimg","root","");
$query = "UPDATE attempt010 SET
caption='$imgcap' WHERE id='$ids'";
echo $query;
$sql=$con->prepare($query);
$sql->execute();
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
}
}
}
?>
This code looks like it can't work. Because you have submit and form handling code in same page. The idea behind form is to post data to different page(set in form action) and this page will do something with this data and display results to the user. For your example to work make form in your first file like:
<form action="addcap.php">
<inputs here>
</form>
Nowadays it is common that database operations are done asynchronic on server side, when user can continue using the page/app.
So learn how to use jQuery and AJAX. Maybe nodeJS or other new stuff.

PDO PHP Array issue

function chkQuestions($info)
{
$query = $this->handle->prepare("SELECT * FROM tbltest");
$query->execute();
$rows = $query->fetchAll();
$getPost = $query->rowCount();
foreach($rows as $row) {
for($i = 1; $i <= $getPost; $i++) {
$answerID[$i] = array($info['answer'.$i]);
$lo = array($answerID);
}
foreach($answerID as $question) {
if(array_key_exists($row['answer'],$question)) {
$test = "found";
return $test;
} else {
return $question;
}
}
}
}//chkQuestions
Above is my function, all works, but when I compare the row in my database called answer with the array it doesn't work?
I tried hard coding in the value and it works correctly but not with the array.
I checked to see the values of array and the value is indeed there.
In logic $answerID[$i] = array($info['answer'.$i]); = option1 and if the array value option1 = the database row answer which is set to option1 than return found, but it tells me it cannot find it.
array(1)
{
[0]=> string(7) "option1"
}
Above is the dum_var of the array $question. Any help?
foreach($questions as $question)
{
?>
<h3><?php echo $question['question'] ?></h3>
<div class = "col-xs-12">
<input type="radio" name="answer<?php echo $question['testID'] ?>" id="answer<?php echo $question['testID'] ?>" value="<?php echo $question['option1']?>" />
<label for="question-1-answers-A">A)<?php echo $question['option1'] ?> </label>
</div>
<div class = "col-xs-12">
<input type="radio" name="answer<?php echo $question['testID'] ?>" id="answer<?php echo $question['testID'] ?>" value="<?php echo $question['option2']?>" />
<label for="question-1-answers-B">B)<?php echo $question['option2'] ?></label>
</div>
<div class = "col-xs-12">
<input type="radio" name="answer<?php echo $question['testID'] ?>" id="answer<?php echo $question['testID'] ?>" value="<?php echo $question['option3']?>" />
<label for="question-1-answers-C">C)<?php echo $question['option3'] ?></label>
</div>
<div class = "col-xs-12">
<input type="radio" name="answer<?php echo $question['testID'] ?>" id="answer<?php echo $question['testID'] ?>" value="<?php echo $question['option4']?>" />
<label for="question-1-answers-D">D)<?php echo $question['option4'] ?></label>
<br>
<br>
</div>
<?php
}
echo "<input type='hidden' name='subaction' id='subaction' value='chkQuestion'> <button class='btn btn-primary' name='submit' type='submit'>Submit</button> </form>";
}
else
echo "No Quiz Found </form>";
?>
</div>
I don't have a lot of confidence in my answer because your coding method does a good job of confusing me. However, I feel like I need to get something on the page so we have some sort of solid base to work from:
function chkQuestions($info){
$check=array(); // this will hold the results to return
$stmt=$this->handle->prepare("SELECT `testID`,`answer` FROM tbltest");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
if($info['answer'][$row['testID']]==$row['answer']){
$check[$row['testID']]="correct";
}else{
$check[$row['testID']]="incorrect";
}
}
return $check; // handle this however you like on your main page
}

Foreach : if current item value is empty, get the value of the last iteration

I'm using a foreach to save in database my form datas.
And, sometimes some values are empty because it's the same as the last value entered. I would like (if the current iteration value is empty) to get the last iteration value and to print it.
Do you have a solution?
Thank you!
<?php
$html = file_get_contents("Intranet link");
function parseTable($html){
$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = true;
$tables = $dom->getElementById('tblResultats');
$rows = $tables->getElementsByTagName('tr');
return $rows;
}
$rows = parseTable($html);
$i = 1;
$count = 0;
foreach ($rows as $row){
if($i <> 1 ){
$cols = $row->getElementsByTagName('td');
if (preg_match('/visite/i',$cols->item(0)->nodeValue)) {
$count = $count-1;
}else{
$cols->item(6)->nodeValue = str_replace(' ', '', $cols->item(6)->nodeValue);
$train_nbr = preg_replace("/[^0-9,.]/", "", $cols->item(6)->nodeValue);
if($train_nbr == ""){
$train_nbr = "00000";
}
?>
<div id="criter_<?php echo $count; ?>" class="panel <?php if($cols->item(4)->nodeValue == " -Z"){ echo "panel-z-series"; }elseif($cols->item(4)->nodeValue == " -X"){ echo "panel-x-series"; }elseif($cols->item(4)->nodeValue == " BB"){ echo "panel-bb-series"; }elseif($cols->item(4)->nodeValue == " -B"){ echo "panel-b-series"; } ?>">
<input type="hidden" name="trainid_<?php echo $count; ?>" value="<?php echo $train_nbr; ?>">
<input type="hidden" name="traintype_<?php echo $count; ?>" value="<?php echo $cols->item(4)->nodeValue; ?>">
<input type="hidden" name="userid_<?php echo $count; ?>" value="<?php echo $_SESSION["Auth"]["username"]; ?>">
<input type="hidden" name="entrydate_<?php echo $count; ?>" value="<?php echo date("d/m/Y"); ?> <?php echo $cols->item(2)->nodeValue; ?>">
<input type="hidden" name="leftdate_<?php echo $count; ?>" value="<?php echo $cols->item(8)->nodeValue; ?>">
<input type="hidden" name="openeddate_<?php echo $count; ?>" value="<?php echo date("d/m/Y H:i:s"); ?>">
<input type="hidden" name="entrynumber_<?php echo $count; ?>" value="<?php echo $cols->item(0)->nodeValue; ?>|<?php echo $cols->item(1)->nodeValue; ?>">
<input type="hidden" name="leftnumber_<?php echo $count; ?>" value="<?php echo $cols->item(7)->nodeValue; ?>|<?php echo $cols->item(9)->nodeValue; ?>">
<div class="panel-heading">
<button onclick='addValue();$("#criter_<?php echo $count; ?>").remove();' class="btn btn-default"><i class="fa fa-trash"></i></button>
<strong><?php echo $cols->item(2)->nodeValue; ?> </strong>
<div style="font-size:18px;margin-top:-30px"><?php if($cols->item(4)->nodeValue == " -Z"){ echo "<strong>Z</strong>"; }elseif($cols->item(4)->nodeValue == " -X"){ echo "<strong>X</strong>"; }elseif($cols->item(4)->nodeValue == " BB"){ echo "<strong>BB</strong>"; }elseif($cols->item(4)->nodeValue == " -B"){ echo "<strong>B</strong>"; } echo $train_nbr; ?></div>
<span class="pull-right">
<div class="input-group date picker" >
<input type="text" class="form-control" value="<?php echo $cols->item(8)->nodeValue; ?>"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</span>
<br>
<!-- If values from current iteration are empty, get the values from the -1 iteration -->
Train numéro <strong><?php echo $cols->item(0)->nodeValue; ?></strong> en provenance de <strong><?php echo $cols->item(1)->nodeValue; ?></strong> et à destination de <strong><?php echo $cols->item(9)->nodeValue; ?></strong> (<strong><?php echo $cols->item(7)->nodeValue; ?></strong>)
</div>
<div class="panel-body">
<div id="room_criter_<?php echo $count; ?>">
<p>
Commentaire sur l'engin :<br>
<input type="text" style="width:100%;display: inline-block;margin-bottom:8px;" name="comments_<?php echo $count; ?>" placeholder="Commentaire éventuel sur cet engin (imprévu par exemple)" class="form-control">
Planification des événements :<br>
<input type="text" style="width:70%;display: inline-block;margin-bottom:8px;" name="eventcriter_<?php echo $count; ?>[]" placeholder="Evènement ou intervention planifiée sur cet engin" class="form-control">
<input type="hidden" name="lastmodified_<?php echo $count; ?>[]" value="<?php echo $_SESSION['Auth']['username']; ?>" class="form-control">
<select style="width:19%;display: inline-block;" class="form-control" name="eventcriterstatus_<?php echo $count; ?>[]">
<option value="0" selected>Non effectuée</option>
<option value="1">En cours</option>
<option value="2">Terminée</option>
</select>
<a style="display: inline-block;border-radius: 4px;" class="btn btn-success" onclick="add_fields(<?php echo $count; ?>);"><span class="fa fa-plus"></span> Ajouter</a>
</p>
</div>
</div>
</div>
<?php
}
}
$i++;
$count++;
}
?>
I'm not sure if I understood the task right, but here's my try.
for ($i = 2, $n = count($rows); $i < $n; ++$i) {
$row = $rows[$i - 1];
$prevRow = $rows[$i - 2];
$cols = $row->getElementsByTagName('td');
$prevCols = $prevRow->getElementsByTagName('td');
$values = [];
for ($j = 0; $j < ITEMS_COUNT; ++$j) {
$value = $cols->item($j)->nodeValue;
if (empty($value)) {
$value = $prevCols->item($j)->nodeValue;
}
$values[$j] = $value;
}
//And then you can use $values[$j] instead of $cols->item($j)->nodeValue.
}

Passing checkbox values into an array?

I have set up a group of checkboxes. They are dynamic, so the number of checkboxes will be different dependent on the person using the site. The structure of how the checkboxes are created is:
<label for="plabackformat-holder-label">Format</label>
<div class=" playbackformat-holder-<?php echo $num; ?> playbackformat-holder">
<div class="playback-format-radio-buttons">
<label for="notset-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="notset" name="playback_format[<?php echo $second_num; ?>]" id="notset-<?php echo $num; ?>" <?php if($field['playback_format'] == 'notset') { echo 'checked'; } ?>>None
</label>
<label for="dvd-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="dvd" name="playback_format[<?php echo $second_num; ?>]" id="dvd-<?php echo $num; ?>" <?php if($field['playback_format'] == 'dvd') { echo 'checked'; } ?>>DVD
</label>
<label for="bluray-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="bluray" name="playback_format[<?php echo $second_num; ?>]" id="bluray-<?php echo $num; ?>" <?php if($field['playback_format'] == 'bluray') { echo 'checked'; } ?>>Bluray
</label>
<label for="3d-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="3d" name="playback_format[<?php echo $second_num; ?>]" id="3d-<?php echo $num; ?>" <?php if($field['playback_format'] == '3d') { echo 'checked'; } ?>>3d
</label><br />
</div>
</div>
My save function is:
$new = array();
for ( $i = 0; $i < $count; $i++ ) {
$new[$i]['playback_format'] = $playbackFormats[$i];
}
I've been reading up on this issue and it seems its because my input fields do not contain unique names. I'm trying to store the data into an array, so it would be ['playback_format'] => dvd,3d,bluray or something similar.
Right now its only storing the last checked value. Is there a way I can use a forloop or something to iterate over the checked values and push them into my array??
You can just get rid of the "$second_num" in each <input name="playback_format[]"/> html tag. This will put everything into an array for you once you submit the form. You can check this by adding this line to the page as a test.
<?php print_r($_REQUEST['playback_format']); ?>
Generally, You want to avoid any loop if they aren't required.
Hope that helps with what you are doing.
What is $second_num? Does it need to be a part of the input name?
You can get PHP to recognise the submitted values as an array if you do it this way:
<input name="playback_format[<?php echo $second_num; ?>][]">
Or if you don't need $second_num as part of the name, just:
<input name="playback_format[]">
$_POST['playback_format'] will then be an array containing all the selected options.
There is a section in the PHP docs specifically about this behaviour.
Checkboxes have all the same name in your example. Name it differently like :
<label for="plabackformat-holder-label">Format</label>
<div class=" playbackformat-holder-<?php echo $num; ?> playbackformat-holder">
<div class="playback-format-radio-buttons">
<label for="notset-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="notset" name="playback_format_notset" id="notset-<?php echo $num; ?>" <?php if($field['playback_format_notset'] == 'notset') { echo 'checked'; } ?>>None
</label>
<label for="dvd-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="dvd" name="playback_format_dvd" id="dvd-<?php echo $num; ?>" <?php if($field['playback_format_dvd'] == 'dvd') { echo 'checked'; } ?>>DVD
</label>
<label for="bluray-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="bluray" name="playback_format_bluray" id="bluray-<?php echo $num; ?>" <?php if($field['playback_format_bluray'] == 'bluray') { echo 'checked'; } ?>>Bluray
</label>
<label for="3d-<?php echo $num; ?>">
<input type="checkbox" class="playbackformat-holder-radiobutton" value="3d" name="playback_format_3d" id="3d-<?php echo $num; ?>" <?php if($field['playback_format_3d'] == '3d') { echo 'checked'; } ?>>3d
</label><br />
</div>
</div>
And Try this in PHP :
//WHen you want to see what is send in Post :
var_dump($_POST);
//So, for get result :
$tab = array();
foreach($_POST as $key =>$value){
$tab[$key] = $value;
//Display it
echo $key . "=" . $value;
}

if statement is equal to a value

I have a result(string) of 1,1,0,0 - These come from $sub_array['state']
Currently all of my check boxes are checked. How can I code the code below so that if its 1 its checked else its not? as the current code gives them all 'checked'
<?php
foreach($assoc_categories as $sub_array)
{
if($sub_array['state'] == 1)
{
$checked_state = " checked='checked'";
}
?>
<div>
<input
class="checkbox"
type="checkbox"
name="product_category"
class="product_category_selector"
id="product_category_<?php echo $sub_array['cat_id']; ?>"
data-id="<?php echo $sub_array['cat_id']; ?>"
<?php echo $checked_state; ?>
/>
<?php echo $sub_array['name']; ?>
</div>
<input
class="order"
type="input"
value="<?php echo $sub_array['sorder']; ?>"
/>
<?php
}
?>
Change:
if($sub_array['state'] == 1)
{
$checked_state = " checked='checked'";
}
To:
if($sub_array['state'] == 1)
{
$checked_state = " checked='checked'";
} else
{
$checked_state = "";
}
Basically, you are not clearing the previous value as the loop continues.
Alternatively, you could use:
$checked_state = ($sub_array['state'] == 1) ? " checked='checked'" : "" ;
You forget to reset checked_state or reset it to '' if $sub_array['state'] is equal to 0.
<?php
$assoc_categories = array(
array('state'=>1, 'cat_id'=>1, 'name'=>'one', 'sorder'=>1),
array('state'=>1, 'cat_id'=>2, 'name'=>'three', 'sorder'=>2),
array('state'=>0, 'cat_id'=>3, 'name'=>'four', 'sorder'=>3),
array('state'=>0, 'cat_id'=>4, 'name'=>'five', 'sorder'=>4),
);
foreach($assoc_categories as $sub_array)
{
$checked_state = $sub_array['state'] == 1 ? " checked='checked'" : '';
?>
<div>
<input
class="checkbox"
type="checkbox"
name="product_category"
class="product_category_selector"
id="product_category_<?php echo $sub_array['cat_id']; ?>"
data-id="<?php echo $sub_array['cat_id']; ?>"
<?php echo $checked_state; ?>
/>
<?php echo $sub_array['name']; ?>
</div>
<input
class="order"
type="input"
value="<?php echo $sub_array['sorder']; ?>"
/>
<?php
}

Categories