Processing HTML checkbox forms with PHP - php

I am generating a checklist based on mysql data in an HTML form. When the submit button is clicked the php script changes the "complete" field in the mysql database. How can I process more than one item at a time with lists that have variable lengths? Currently when I click more than two boxes, only one gets processed.
Here's the HTML form:
<form method='post' action='listprocessor.php'>
<input style="float:right" type='checkbox' name='complete_goal' value='61'>Milk</input>
<input style="float:right" type='checkbox' name='complete_goal' value='117'>Eggs</input>
<input style="float:right" type='checkbox' name='complete_goal' value='118'>Bread</input>
<input style="float:right" type='submit' name='submitbtn' value='Completed'></input>
</form>
and here's the simplified php:
$_POST['submitbtn'];
$completed_goal = $_POST['complete_goal'];
$query = mysql_query("UPDATE notes SET complete='1' where note_id='$completed_goal'");

Your input element name should be an array, such as complete_goal[].
<input style="float: right;" type="checkbox" name="complete_goal[]" value="61">Milk</input>
You can update them all in a single query using a WHERE note_id IN (<?php echo implode( ',', $_POST['completed_goal'] ); ?>).
$query = mysql_query( "UPDATE `notes` SET `complete` = '1' WHERE `note_id` IN (" . implode( ',', $_POST['completed_goal'] ) . ")" );

Should work and hope it helps. Afaik are all inputs with same name are treated like radiobuttons. So you have to create an array with all checkboxes.
<form method='post' action='listprocessor.php'>
<input style="float:right" type='checkbox' name='complete_goal[]' value='61'>Milk</input>
<input style="float:right" type='checkbox' name='complete_goal[]' value='117'>Eggs</input>
<input style="float:right" type='checkbox' name='complete_goal[]' value='118'>Bread</input>
<input style="float:right" type='submit' name='submitbtn' value='Completed'></input>
</form>
<?php
if(isset($_POST['complete_goal']))
{
$query = mysql_query("UPDATE `notes` SET `complete`='1' WHERE `note_id` IN ('".implode("','", array_values($complete_goal))."');");
}
?>
EDIT: Added Chris N' idea of mysql update.

I'd use a unique name attribute for each checkbox, then grab all of the checkboxes in the script you're using for submit handling and do
foreach($post_fields as $post_field_name) {
if(isset($_POST[$post_field_name])) {
// do your query
}
}

Perhaps this will work (might have to check syntax as it was off the top of my head). any checkbox that isnt' checked should not be listed in the $complete_goals array so you're safe to process them all :)
foreach ($_REQUEST['complete_goal'] as $key) {
$query = mysql_query("UPDATE notes SET complete='1' where note_id='$key'");
}

Related

How to store HTML form value for other pages in PHP and MySQLi?

I have created a database in phpMyAdmin with table for topics such as Math, Physics etc. Each topic has a topic_id as primary key in table tb_topic. Each topic can have multiple videos. Admin can add videos to each topic which requires topic_id as foreign key in table tb_video_management to store videos against a topic.
Backend:
There is a button to add videos in form.php
form.php:
<?php
$query = "SELECT topic_id, topic_name,aid FROM tb_topic";
$result = $con->query($query);
while($query_row = mysqli_fetch_assoc($result)) {?>
<tr>
<td><form action='edit.php' method='get'>
<button type='submit' name='edit' id = 'edit' value='<?php echo $query_row['topic_id'];?>' class='btn btn-success'>EDIT</button><br />
</form></td>
</tr>
<?php
} ?>
When this button is clicked, page is navigated to another page "edit.php" which has 2 buttons, one for add new video and second for viewing video gallery.
edit.php:
$id = $_GET['edit'];
echo 'topic id----> ' . $id;
<form action='add_video.php' method='get'>
<button type='submit' name='add' id = 'add' value='<?php echo $id;?>' class='btn btn-success'>ADD NEW VIDEO</button>
</form>
<form action="video.php" method="get">
<button type="submit" name="goback" id="goback" value="submit" class="btn btn-primary">VIEW GALLERY</button>
</form>
The class where videos are added has a form for topic name, details etc.
add_video.php
$id = $_GET['add'];
echo 'topic id----> ' . $id;
<form action="add_video.php" method="post">
Video Title: <input type="text" name="video_name"><br />
Video Detail: <input type="text" name="video_detail"><br />
Video Question: <input type="text" name="video_question"><br />
Video Link: <input type="text" name="video_link"><br />
<input type="submit" name="submit" value = "Submit"><br />
</form>
When "submit" button is clicked, following code executes:
if(isset($_POST['submit'])) {
if(!(empty($_POST['video_name']) || empty($_POST['video_detail']) || empty($_POST['video_question']) || empty($_POST['video_link']))) {
$name = $_POST['video_name'];
$detail = $_POST['video_detail'];
$question = $_POST['video_question'];
$link = $_POST['video_link'];
$insert = "INSERT INTO tb_video_management(topic_id, video_name, video_detail, video_question,video_link) VALUES ('$id','$name','$detail', '$question','$link')";
if(!mysqli_query($con,$insert))
echo "error";
header('location:edit.php');
}
}
The problem I am facing is, when I click submit button, the value in $id is lost (may be because another button (submit) is pressed) and it fails to insert the record as there is no value for "topic_id" anymore. I cannot resolve this issue of keeping foreign key value even after pressing submit button.
So far I have been creating extra table to hold value for topic_id which is definitely not the right approach.
To use the $id into another page, you must have to store that in such a way that it will be remain exist after submit.That can be done by using the hidden field.
You may set the value of $id like:
<input type="hidden" name="topic_id" value="<?php echo $id?>">
Once you submit and redirect to add_video.php, you may get the value of $id same as another field video_detail.
On submit look like:
if(isset($_POST['submit'])) {
$topic_id = $_POST['topic_id'];
}

How to get value from input box and store it in php variable?

I'm working on this website and I can't seem to get some things to work.
I have 3 inputs in my html:
<form action='' method='post'>
<input id='counterName' name='counterName' type='text' value='nothing'></input>
</form>
<form action='' method='post'>
<input type='text' value='3' name='counterNum' class='counter'></input>
</form>
<form action='' method='post'>
<input type='submit' value='Save' name='save' id='save'></input>
</form>
I want to get the value of the first two (counterName and counterNum) and store it in 2 variables when I click on the Save button. So I did:
if(isset($_POST['save'])){
$counterName = $_POST['counterName'];
$counterNum = $_POST['counterNum'];
$prefix = mysql_real_escape_string("`~");
}
You will see where $prefix is used in a second.
Next I want to take those three variables and save them to my MySql's database column by concatenating in the following format. "~$counterName~$counterNum". Here is how I did it:
mysql_query("UPDATE `users` SET `counter` = CONCAT (`counter`,'$prefix') WHERE `userID` = '$userID'");
mysql_query("UPDATE `users` SET `counter` = CONCAT (`counter`,'$counterName') WHERE `userID` = '$userID'");
mysql_query("UPDATE `users` SET `counter` = CONCAT (`counter`,'$prefix') WHERE `userID` = '$userID'");
mysql_query("UPDATE `users` SET `counter` = CONCAT (`counter`,'$counterNum') WHERE `userID` = '$userID'");
My issue is that when I see what the column "counter" holds I see this: "~~" without the variables in between. What am I doing wrong? Btw the type of the column is VARCHAR.
Thank you.
As Sadikhasan said in Comments, you should add inputs in a single form like this:
<form action='' method='post'>
<input id='counterName' name='counterName' type='text' value='nothing'></input>
<input type='text' value='3' name='counterNum' class='counter'></input>
<input type='submit' value='Save' name='save' id='save'></input>
</form>
this should solve your problem.

PHP Mysql - Delete button keeps on deleting latest row

When i run into a glitch, I always find find the answer on StackOverflow, but this time, although I'm sure the fix is easy, I just can't seem to get it right !
Basically, i'm trying to add a "delete" button next to each row fetched from my mysql database. The users should be able to delete a specific post, if needed.
When i hit the delete button, it's always the latest row that gets deleted. So i guess there's something wrong with the value passed in each row : seems like they're overridden by the latest one.
Below's my code:
<?php
$table = query("SELECT post, postid FROM post_list WHERE id = ? ORDER BY
time DESC LIMIT 15", $_SESSION["id"]);
foreach ($table as $row)
{
$post = $row["post"];
$postid = $row["postid"];
echo ("<table>");
echo ("<tr>");
echo("<td>" . $post . "</td>");
echo("</td>")?>
<div id="posteraser">
<form action='' method='post'>
<input type='hidden' name='postid' value='<?php echo $postid?>'>
<input type='submit' name='posteraser'>Delete</input>
</form>
</div>
<?php
echo ("</td>");
echo ("</tr>");
echo ("</table>");
echo '<hr>';
}
?>
And below on the same page, there's the delete button code:
<?php
if(isset($_POST['posteraser']))
{
$sql = query("DELETE FROM post_list WHERE postid = '$postid' ");
redirect ('home.php');
}
?>
Any help/tips will be much appreciated !
Thanks a lot !
You have to pass here the $_POST['postid']
if(isset($_POST['posteraser'])){
$postid = $_POST['postid'];
$sql = query("DELETE FROM post_list WHERE postid = '$postid' ");
redirect ('home.php');
}
OR as procedure way
$sql = query("DELETE FROM post_list WHERE postid = ? ",$postid);
A developer should always be aware of the HTML code they create with their PHP code.
It's essential thing.
As a matter of fact, HTML code is the very result of our efforts. NOT nice picture on can see in the browser windows - it's browser's job - but the very HTML code.
So, if you bother to see into generated code, you would discover something that can be boiled down to
<input type='hidden' name='postid' value='1'>
<input type='hidden' name='postid' value='3'>
<input type='hidden' name='postid' value='4'>
<input type='hidden' name='postid' value='5'>
<input type='hidden' name='postid' value='9'>
Do you have any questions why you have only last value?
Speaking of solutions, you have two choices
create a separate form for the every row
mark the very Delete button with id.
<input type='submit' name='posteraser[<?php echo $postid?>]'>Delete</input>
for example
let's check the logic from select statement.
you are selecting postid and assigning it to a hidden element and when you press delete button
that hidden id is sent to server.
so form creating under for loop is
<div id="posteraser">
<form action='' method='post'>
<input type='hidden' name='postid' value='<?php echo $postid?>'>
<input type='submit' name='posteraser'>Delete</input>
</form>
</div>
but hidden element is creating with same name for each row.
so when you press delete button . first hidden id is sent to server.
and this hidden id is already newest as from your select statement.
so what's the solution for it..
either you should sent postid through get attaching it in your url so that you can identify
which delete button is pressed.
or create a logic to send only that id on which delete is pressed.
This looks wrong:
echo ("<tr>");
echo("<td>" . $post . "</td>");
echo("</td>")?>
The trailing </td> shouldn't be there. Something else perhaps?
Also, you don't show how postid gets into $_SESSION['id']

request in while loop

I work with this code:
<form method="get" name="MobileDetails">
<input name="brand" id="brand" value="<?php echo $brand;?>" type="hidden">
<input name="brid" id="brid" value="<?php echo $brandid;?>" type="hidden">
<button type="button" name="submitButton" value="get Details" onclick="getDetails()">
</form>
java script
<script type="text/javascript">
function getDetails(){
var brand = document.getElementById('brand').value;
var brandid = document.getElementById('brid').value;
document.MobileDetails.action = 'details.php?brand='+brand+'&id='+brandid;
document.MobileDetails.submit();
}
</script>
But it does not work in while loop. Whats the problem? My code is given below.
When i click on the button it do not do anything. But the code work great with out while loop given on the top.
<?php
require_once('connection.php');
$SQL= "SELECT*FROM mobile ORDER BY price ASC LIMIT 10";
$result= mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)){
$brand=$db_field['brand'];
$id=$db_field['id'];
$model=$db_field['model'];
echo "<form method='get' name='MobileDetails'>";
echo " <input name='brand' id='brand' value='". $brand ."' type='hidden'>";
echo" <input name='brid' id='brid' value='". $id ."' type='hidden'>";
echo" <input name='mod' id='mod' value='". $model ."' type='hidden'>";
echo" <button type='button' name='submitButton' value='get Details' onclick='getDetails()'/>
</form> ";
echo "CLICK HERE";
}
?>
You're using several times the same id. Ids have to be unique.
Uou are dealing with multiple id's. The job of an ID is to be unique identifier for the element. I suggest just using
<form action="details.php" type="get">
this will do exactly what you are trying to achieve without using the function.
The thing with element ID's is that they need to be unique for the page; however, as you may see, not required for HTML to be displayed. When calling your JS function getDetails(), it grabs the element by ID but when you have multiple ID's in the page, this will fail.
So what can you do? Well, in your loop, you create a new form for each 'brand'. You can pass a reference of the form to the grabdetails and then, by NAME, grab the values from that form.
Rather than using Javascript to generate a link based on given details put in a hidden field, you should just generate the action at the PHP level.
echo "<form method='get' name='MobileDetails' action='details.php?brand=$brand&id=$brandid'>";
But since you do have hidden fields, using just action='details.php' the form will take the user to
details.php?brand={brand}&brid={id}&mod={model}
You should look into POST or making your button into a plain link rather than having a form.

DELETE FROM table WHERE ID='$id' — Variable refuses to stick

Trying to perform a very simple task here.
I have an <ol> that contains 4 rows of data in some handy <li>s. I want to add a delete button to remove the row from the table. The script in delete.php appears to have finished, but the row is never removed when I go back and check dashboard.php and PHPMyAdmin for the listing.
Here's the code for the delete button (inside PHP):
Print "<form action=delete.php method=POST><input name=".$info['ID']." type=hidden><input type=submit name=submit value=Remove></form>";
Moving on to delete.php:
<?
//initilize PHP
if($_POST['submit']) //If submit is hit
{
//then connect as user
//change user and password to your mySQL name and password
mysql_connect("mysql.***.com","***","***") or die(mysql_error());
//select which database you want to edit
mysql_select_db("shpdb") or die(mysql_error());
//convert all the posts to variables:
$id = $_POST['ID'];
$result=mysql_query("DELETE FROM savannah WHERE ID='$id'") or die(mysql_error());
//confirm
echo "Patient removed. <a href=dashboard.php>Return to Dashboard</a>";
}
?>
Database is: shpdb
Table is: savannah
Ideas?
It's refusing to stick because you're calling it one thing and getting it with another. Change:
"<input name=".$info['ID']." type=hidden>"
to
"<input name=ID value=".$info['ID']." type=hidden>"
because in delete.php you're trying to access it with:
$id = $_POST['ID'];
You should really quote attribute values as well ie:
print <<<END
form action="delete.php" method="post">
<input type="hidden" name="ID" value="$info[ID]">
<input type="submit" name="submit" value="Remove">
</form>
END;
or even:
?>
form action="delete.php" method="post">
<input type="hidden" name="ID" value="<?php echo $info['ID'] ?>">
<input type="submit" name="submit" value="Remove">
</form>
<?
Please, for the love of the web, don't built an SQL query yourself. Use PDO.
Just another point I'd like to make. I'm 95% sure that you can't give an input a numeric name/id attribute. It has to be like "id_1" not "1".
Also with php you can do arrays.
So you could do this
<input name="delete[2]">
then in your php
if(isset($_POST['delete']))
foreach($_POST['delete'] as $key=>$val)
if($_POST['delete'][$key]) delete from table where id = $val

Categories