Update checkbox value in SQL table - php

I can display checkbox value from a SQL query, but I can't update them, I just can update untick value (0 value), if I untick the checkbox, it can save the untick value 0 to the SQL table. if I retick the checkbox, it cannot update the value in the SQL query. I'm using int as the data type. Here's the sample code from my test system:
Checkbox HTML:
<div class="form-group col-lg-6">
<label class="control-label col-lg-4">Pricing<span style="color:red;"> </span></label>
<div class="col-lg-8">
<input type="checkbox" name="rm_option" id="rm_option" value="1"><strong> RM </strong></input>
<input type="checkbox" name="point_option" id="point_option" value="1"><strong> Full Point </strong></input>
<input type="checkbox" name="partial_option" id="partial_option" value="1"><strong> Partial Point + RM </strong></input>
</div>
</div>
Checkbox echo edit function:
<?php
$sql = "select * from promotion_list where id=" . $_GET['id'];
$arr_sql = db_conn_select($sql);
foreach ($arr_sql as $rs_sql) {
foreach ($rs_sql as $key => $value) {
?>
$("#<?php echo $key ?>").val("<?php echo $value ?>");
<?php if($value == 1){ ?>
$("#<?php echo $key ?>").attr("checked", true).prop("checked", true);
<?php } ?>
<?php
}
?>
$("#filter_id").val('<?php echo $rs_sql['id'] ?>');
$("#promotion_content").jqteVal('<?php echo $rs_sql['promotion_content'] ?>');
$("#promotion_terms").jqteVal('<?php echo $rs_sql['promotion_terms'] ?>');
$("#promotion_instruction").jqteVal('<?php echo $rs_sql['promotion_instruction'] ?>');
$("#promotion_policy").jqteVal('<?php echo $rs_sql['promotion_policy'] ?>');
<?php
}
?>
Update function:
else if($action == 'update') {
$rm_option = isset($_POST['rm_option']) ? $_POST['rm_option'] : "";
$point_option = isset($_POST['point_option']) ? $_POST['point_option'] : "";
$partial_option = isset($_POST['partial_option']) ? $_POST['partial_option'] : "";
$query = "UPDATE " . $table ." SET id_promotion_categories = '" . $id_promotion_categories . "',
promotion_title = '".$promotion_title."',
rm = '".$rm."', promotion_description = '".$promotion_description."',
point = '".$point."', point_rm_point = '".$point_rm_point."', point_rm_rm = '".$point_rm_rm."',
quantity_limit_option = '".$quantity_limit_option."', quantity_limit = '".$quantity_limit."',
discount_percentage = '".$discount_percentage."', promotion_price_before = '".$promotion_price_before."',
promotion_price_after = '".$promotion_price_after."',
redemption_from_date = '".$redemption_from_date."', redemption_to_date = '".$redemption_to_date."',
rm_option = '".$rm_option."', point_option = '".$point_option."', partial_option = '".$partial_option."',
merchant_option = '".$merchant_option."', merchant_price = '".$merchant_price."',
reservation = '".$reservation."', feature = '".$feature."' where id='" . $id . "'";
$arr_treatment = db_conn_update($query);
if ($arr_treatment) {
$result_arr['msg'] = 'Update Successful';
} else {
$result_arr['msg'] = 'Error in processing data. Please try again later.';
}
$result_arr = special_char_display_arr($result_arr);
$json = json_encode($result_arr);
print($json);
}
Below is my output(It can not let me update in the empty checkbox, for example, Partial Point + RM in below):
All update record is no problem, only for the checkbox cannot update. I hope anyone can guide me solve this problem. Thanks a lot.

For checkboxes, the $_POST array element is present (and = 1) if the checkbox is checked, otherwise it is absent. So change
$rm_option = isset($_POST['rm_option']) ? $_POST['rm_option'] : "";
$point_option = isset($_POST['point_option']) ? $_POST['point_option'] : "";
$partial_option = isset($_POST['partial_option']) ? $_POST['partial_option'] : "";
to
$rm_option = isset($_POST['rm_option']) ? 1 : 0;
$point_option = isset($_POST['point_option']) ? 1 : 0;
$partial_option = isset($_POST['partial_option']) ? 1 : 0;
and you should be able to update 0 values as well. Note that as #SergheiLeonenco said, since these are numeric values, you don't need quotes around them in your query.
Mandatory SQL injection commentary.
Because you are using $_POST values directly in your query, you are vulnerable to SQL injection. You should read How can I prevent SQL injection in PHP and move to prepared statements to protect yourself.

Related

How to check which radio button is clicked by PHP $_POST?

I am trying to know which radio button is clicked by PHP in a form with $_POST['...'].
This is my form:
<form action="" method="post" enctype="multipart/form-data">
<div class="input-group">
<span class="input-group-addon">Add:</span>
<input type='radio' name='add1' id='program' value='program' onchange="hideCollege()" checked> Program Intern</input>
<input type='radio' name='add1' id='department_coop' value='department_coop' onchange="showCollegelist()"> Department Cooperation</input>
<input type='radio' name='add1' id='foreigner' value='foreigner' onchange="hideCollege()"> Foreigner Area</input>
</div>
</form>
And I am trying to receive the values of the three radio buttons by:
if(isset($_POST['program'])){
$program = 1;
}
else if(isset($_POST['foreigner'])){
$foreigner = 1;
}
else if(isset($_POST['department_coop'])){
$coop = 1;
$college = $_POST['college'];
$department = $_POST['department'];
}
But it seems that no if statements are true, and turns out that no variables are assigned value. Does anyone know how to get to what I aim to do? Thanks a lot in advance.
Try this below section . Post request value should processed on form name attributes. So must check the conditional form post name value.
if(isset($_POST['add1']) && $_POST['add1']=='program' ){
$program = 1;
}
else if(isset($_POST['add1']) && $_POST['add1']=='foreigner' ){
$foreigner = 1;
}
else if(isset($_POST['add1']) && $_POST['add1']=='department_coop' ){
$coop = 1;
$college = $_POST['college'];
$department = $_POST['department'];
}
You should check the values of the radio button on the basis of name attribute.
if(isset($_POST['add1']) && $_POST['add1']=='program'){
$program = 1;
}
else if(isset($_POST['add1']) && $_POST['add1']=='foreigner'){
$foreigner = 1;
}
else if(isset($_POST['add1']) && $_POST['add1']=='department_coop'){
$coop = 1;
$college = $_POST['college'];
$department = $_POST['department'];
}
Then you will get the checked value.
If you access $_POST['add1'] check for the value as it should either be program, department_coop or foreigner (in this case)

Passing information using post method without session variables

I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>

Count filled SQL array fields PHP

I´m fetching an array from a mysql query like this.
$viewerSQL = mysql_query("SELECT * FROM `this` WHERE id = ".
mysql_real_escape_string($_GET[id]) ."");
$pageData = mysql_fetch_array($pageSql);
I get an array with like 40 entries, i want to check seven of them by name if they are filled.
What i´ve tried and what I thought about so far:
$oioi = 0;
while($oioi<7){
$oioi++;
$pic = "pic".$oioi;
$active="";
$path = "./upload/objectoffers/$viewerData[id]/$pic";
$picDesc = "pic".$oi."Desc";
$picArray = '$viewerData['.$pic.']';
echo $pic."<br>";
echo $picArray."<p>";
if(!empty($path)){
if($oioi==1){$active = "active";}?>
<div class="item <?=$active;?>">
<img style="width: 100%;" src="./images/<?=$viewerData[$pic];?>" alt="<?=$viewerData[$picDesc]?>">
</div>
<?
}}
?>
But this doesn´t work because: $path is NEVER empty...I wanted to avoid to write "if(!empty)" for every single $viewerData[pic1] to $viewerData[pic7] array manual...
that´s why i´m here...
maybe you can help me improving this or offer some tips.
Thanks!
edit: This is what I get as "output":
pic1
$viewerData[pic1]
pic2
$viewerData[pic2]
pic3
$viewerData[pic3]
pic4
$viewerData[pic4]
pic5
$viewerData[pic5]
pic6
$viewerData[pic6]
pic7
$viewerData[pic7]
I think you should use file_exists instead !empty:
$oioi = 0;
while ($oioi < 7) {
$oioi++;
$pic = "pic" . $oioi;
$active = "";
$path = "./upload/objectoffers/$viewerData[id]/$pic";
$picDesc = "pic" . $oi . "Desc";
$picArray = '$viewerData[' . $pic . ']';
echo $pic . "<br>";
echo $picArray . "<p>";
if (file_exists($path)) {
if ($oioi == 1) {
$active = "active";
}
?>
<div class="item <?= $active; ?>">
<img style="width: 100%;" src="./images/<?= $viewerData[$pic]; ?>" alt="<?= $viewerData[$picDesc] ?>">
</div>
<?php
}
}

creating a dynamic search query in php and pdo

Ive been trying to get this to work but I dont think my sql is setup correctly.
For instance I am trying to get a search word from the URL and then insert it using prepared statements so that its safe to use in the database.
First I call the userid of the products they own from the sessions.
Then I check if they have more than 1 item, if they do I setup an array and insert into database, if they do not have more than 1 item then I just simply insert into database to retrieve data.
The reason why I am setting it into variables is because its being sent to the pagination class so it will paginate the results.
Here is the header of the html:
<?php
$searchword = $urlmaker->geturlandsearch($_GET["search"]);
$findcomma = strpos($_SESSION["SESS_USERSPRODUCTIDS"], ",");
if($findcomma == true){
$userproductid = explode(',', $_SESSION["SESS_USERSPRODUCTIDS"]);
$prep = array(':like' => "%$searchword%", ':like2' => "%$searchword%");
$q = '';
$e = '';
$i = 1;
foreach($userproductid as $productid){
$q .= 'productid=:productid' . $i . ' || ';
$prep[":productid{$i}"] = $productid;
$i++;
}
$q = rtrim($q, " || ");
} else {
$q = 'productid=:productid';
$prep = array(':productid' => $_SESSION["SESS_USERSPRODUCTIDS"], ':like' => "%$searchword%", ':like2' => "%$searchword%");
}
$maxlimit = 15;
$geturi = "/Search-Forum/" . $_GET['search'] . "/";
$string = "SELECT id,title,date,username,viewcount,replycount,replyuser,replydate FROM forum_topics WHERE " . $q . " AND title LIKE :like OR content like :like2 ORDER BY replydate DESC";
$pagstring = "SELECT id FROM forum_topics WHERE " . $q . " AND title LIKE :like OR content like :like2";
$pagurl = $geturi;
Here is the frontend code:
<?php
$topicQuery = $pagination->paginatedQuery($pdo, $string, $maxlimit, $prep);
if($topicQuery != "no query"){
while($fetchquery = $topicQuery->fetch()) {
$topicid = stripslashes($fetchquery["id"]);
$topictitle = stripslashes($fetchquery["title"]);
$topicdate = stripslashes($fetchquery["date"]);
$topicusername = stripslashes($fetchquery["username"]);
$topicviewcount = stripslashes($fetchquery["viewcount"]);
$topicreplycount = stripslashes($fetchquery["replycount"]);
$topicreplyuser = stripslashes($fetchquery["replyuser"]);
$topicreplydate = stripslashes($fetchquery["replydate"]);
?>
<li>
<div class="topiclisttitle"><p><b><?php echo ucwords($topictitle); ?></b><br><?php echo $topicusername ; ?> on <?php echo $betterTime->dateAndtime($topicdate); ?></p></div>
<div class="topiclistview"><p><b><?php echo $topicviewcount ; ?></b><br>Views</p></div>
<div class="topiclistview"><p><b><?php echo $topicreplycount ; ?></b><br>Replies</p></div>
<div class="topiclistlastposted"><?php if(!empty($topicreplyuser)){ ?><p>By: <b><?php echo $topicreplyuser ; ?></b> On<br><?php echo $betterTime->dateAndtime($topicreplydate); ?></p><?php } else { ?><p>By: <b><?php echo $topicusername ; ?></b> On<br><?php echo $betterTime->dateAndtime($topicreplydate); ?></p><?php } ?></div>
</li>
<?php } } else { ?>
<li><p class="morepadding">No Topics Regarding Your Search Words :(</p></li>
<?php } ?>
Here is the database input on the pagination class:
$freebiesquery = $pdo->prepare($string . " LIMIT " . $maxlimit);
$freebiesquery->execute($prep);
$freebiesquery_num = $freebiesquery->rowCount();
All this works on other pages so it has to be the way Im doing the header section of the code, the way im formating the sql query in the first place.
The only errors I am getting are as follows:
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number
And
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number
But this cant be as I have counted thema and they are the same?
Putting strings containing => into an array doesn't make associations. => is part of the syntax of array literals, they have to be outside the strings.
Replace:
$prep[] = "':productid{$i}' => {$productid}";
with:
$prep[":productid{$i}"] = $productid};
Replace:
$e = "':productid' =>" . $_SESSION["SESS_USERSPRODUCTIDS"];
With:
$prep = array(':productid' => $_SESSION["SESS_USERSPRODUCTIDS"]);
Replace:
$prep = array($e, ':like' => "%$searchword%", ':like2' => "%$searchword%");
with:
$prep[':like'] = "%$searchword%";
$prep[':like2'] = "%$searchword%";

Array doesn't appear to be holding data

I have a system where I rearrange navigational items.
It stores the new order in an array and then I use a for loop to go through the array and update the database.
<?php
$apageid = array();
$apagename = array();
$apageorder = array();
$q = "SELECT g.id, g.title, n.order FROM tbl_general g INNER JOIN tbl_navigation n ON n.pageid = g.id WHERE n.type = '$_SESSION[parent]' ORDER BY n.order";
$return = $database->query($q);
while($row=mysql_fetch_assoc($return)){
$apageid[] = $row['id'];
$apagename[] = $row['title'];
$apageorder[] = $row['order'];
}
$count = count($apageid);
$bpageid = array();
$bpageorder = array();
?>
<div class="form-holder">
<?php
//run through each page one at a time and update the order of the menu
mysql_data_seek( $return, 0 ); //reset the pointer to do the same query
$i = 0; //the count for saving the new configuration
while($row=mysql_fetch_assoc($return)){
$id = $row['id'];
$title = $row['title'];
$order = $row['order'];
?>
<div class="form-row">
<div class="form-label">
Page Name
</div>
<div class="form-field">
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
<?php
for($j=0; $j<$count; $j++){
if($apageid[$j] == $id) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageid[$j]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apagename[$j]; ?></option>
<?php
}
?>
</select>
<select class="select-small" name="<?php echo $bpageorder[$i]; ?>">
<?php
for($k=0; $k<$count; $k++){
if($apageorder[$k] == $order) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageorder[$k]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apageorder[$k]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<?php
$i++;
}
?>
This first chunk of code is the menu where you can reorder items.
Initially it loads up the current select and allows you to change the ordering.
function reorderChildren($pageid, $pageorder){
global $database;
$count = count($pageid);
//run through each page one at a time and update the order of the menu
for($i=0; $i<$count; $i++){
//set a few variables
$pid = $pageid[$i];
$porder = $pageorder[$i];
echo "pid = $pid porder = $porder";
$q = "UPDATE tbl_navigation SET order = '$porder' WHERE pageid = '$pid' AND type = '$_SESSION[parent]'";
$database->query($q);
}
return 0;
}
The information then ends up being passed here and the problem appears to be the for loop is never executed.
Can anyone see why this would be?
It's not the naming used, I've checked them.
Am I storing information in the arrays correctly?
Can I make it clear that it's $bpageid and $bpageorder that are the arrays carrying the information forward.
Thanks!
Was a simple fix!
The problem was that the select name needed to be just name="bpageid[]" rather than what I listed above. Silly!
You have just initilized $bpageid = array(); at top after first while loop.No value is assigned
after that you using
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
but no value is in $bpageid[$i] so name of this select box is blank.
It might be problem. check this and do as required.
you could try to construct a json from the options of the select element store it to a hidden field or send ajax request to php script for processing , order could be made from a "weight" value 1,2,3 etc.... sort it with php and loop to display

Categories