PHP 'Checkbox' Alternative when updating - php

I have a small problem with my PHP Code and as always, any help is hugely appreciated.
The code was originally designed by another person and I seem to have come across a problem that I can't fix.
The structure of the page is as follows:
A while loop to output the data, each of course, has a unique id.
A checkbox that must be ticked before pressing the 'update' button
(several update buttons present pending on how many rows are
returned.
This is what i'm confused on, he has designed it to they must tick the 'checkbox' before pressing update, otherwise, the script doesn't know which 'id' to update. Why is it like this?!
<?php
if($_POST['accept']){
if(!$_POST['check']){
echo "<div class='error_input'>Error! please tick box to confirm </div>";
}else{
$form_id=$_POST['fid'];
$customer=$_POST['customer'];
mysql_query("UPDATE job SET customer='$customer'WHERE f_id=$form_id ");
echo "<div class='form_ok'>Job has been updated.</div>";
}
?>
If I just comment out the check box, and the user clicks the 'accept' button, it doesn't work, so clearly the 'checkbox' is pointing to the unique ID of the row, but I can't see it?
<input type="checkbox" name="check" value="1" required/>
<input type="submit" name="accept" value="Accept Job">
My issue is, I want to be able to remove this annoying checkbox, and once the user has pressed 'accept' add the unique ID into a session, which I know can be done by:
$_SESSION['user_id'] = $user_id;
As they then get redirected to a pop-up box to which I need this unique ID to pull further data from the database.
I've had a go at implemented this:
<input type="submit" name="accept" value="<?php echo"$user_id"; ?>" class="sbutton">
which works in a nutshell, how ever, it's not user friendly and I can't access the user_id, when I use the $_POST feature, it saves the 'name' field.
I know this is long winded, I hope i've given you enough information, many thanks in advance.

It seems like there is another hidden field in there with the job ID, and each row has it's own <form> tags - so if you'll remove the check for the check field than you're fine.
Like that:
<?php
if($_POST['accept'])
{
$form_id=$_POST['fid'];
$customer=$_POST['customer'];
mysql_query("UPDATE job SET customer='".$customer."' WHERE f_id=".$form_id);
echo "<div class='form_ok'>Job has been updated.</div>";
}
?>
By the way - it's best that you'll check and secure the values from the $_POST with check for numbers and securing against SQL Injection with mysql_real_escape_string function

Related

Update MySQL DB with PHP from Checkbox

I am pulling data down from a MySQL table and loading it into a form for editing(updating) a record. Everything is working great until I come the the check boxes. The checkboxes in the form accurately reflect the values in the appropriate columns in the db. But when the person editing changes the checkbox in the edit form it does not pass the data to the database. I have read a ton of checkbox Q&A on stack overflow but don't seem to find what I am looking for. Sorry if this is a redundant Question. Here is the code.
<label for="amenities-beach">
<input class="choose" name="amenitiesB" id="amenities-beach" type="checkbox"
value="<?php echo $row1["amenitiesB"]; ?>"
<?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
Close to Beach</label>
Where amenitiesB in:
value="<?php echo $row1["amenitiesB"]; ?>
is what has been returned from the DB with a SELECT statement with:
$row1 = mysql_fetch_array($result);
But when I change the value in the form and submit it nothing is passed to the variable in the UPDATE statement. Any idea what I am missing? I have 6 of these checkboxes,amenitiesB, amenitiesK, amenitiesS, amenitiesP, amenitiesF, and preferred all with the same code. Any help would be appreciated.
Thank You,
Dave
Ok here is the code: Everything else in the form updates fine. I attempt to pass it to:
$amenitiesB = $_POST['amenitiesB'];
then I put it into the update statement
Hotels.amenitiesB='".$amenitiesB."',
My UPDATE statement is,
$query="UPDATE Hotels
JOIN surfcup_Rates ON Hotels.id = surfcup_Rates.hotelid
SET Hotels.hotel='".$hotel."',
More columns, then
Hotels.amenitiesB='".$amenitiesB."',
Hotels.amenitiesB='".$amenitiesK."',
Hotels.amenitiesB='".$amenitiesS."',
Hotels.amenitiesB='".$amenitiesP."',
Hotels.amenitiesB='".$amenitiesF."',
Hotels.amenitiesB='".$preferred."',
More columns then:
WHERE Hotels.id='".$id."'";
The problem you have comes because when a checkbox is unchecked, by default its data is not transmitted to your PHP, and that's why you have problems by having the UPDATE query parameter empty.
So before your update statement you should have:
$fieldenabled=(bool)(isset($_POST['CHECKBOXNAME']) ? TRUE : FALSE;
And call your UPDATE query with that.
EDIT: Of course you can change $_POST with $_GET depending on the sending method of the <form>
Edit: I think I get the problem. When the box is initially unchecked, the input has an empty value, then when you check it, it passes an empty value in... it will never fill with what you intend the checked value to be. So, instead you need something like this:
<input class="choose" name="amenitiesB" id="amenities-beach" type="checkbox" value="amenity B Selected" <?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
... don't make the "value" attribute dynamic, or else once it becomes empty it will always be empty.
Original Answer:
I assume when you say "change the value in the form" you mean that you uncheck the checkbox... unchecked checkboxes never send any data when you submit the form. You check for "unchecked" status by checking to see if the form variable has been passed at all.
For example:
if (isset($_GET['amenitiesB'])) {
// process with the knowledge that "amenitiesB" was checked
}
else {
// process with the knowledge that "amenitiesB" was unchecked
}
If you mean that you somehow dynamically change the "value" of the checkbox to something else, then I'll need to see the code that accomplishes that.
The main purpose of the "value" attribute in a checkbox input is when you're passing the variable as an array:
<label for="amenities-beach">
<input class="choose" name="amenities[]" id="amenities-beach" type="checkbox" value="<?php echo $row1["amenitiesB"]; ?>" <?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
Close to Beach
</label>
... note specifically that I've changed the "name" attribute from "amenitiesB" to "amenities[]", which, if carried through all of your amenities checkboxes, will give you access to them all in your processing script through the $_GET['amenities'] array (or $_POST, if applicable). Otherwise, there's not much reason to use the "value" attribute of the checkbox input, because you can get all you need just by knowing $_GET['amenitiesB'] is checked (and thus sent with the form) or unchecked (and not sent with the form).

redirect to current page if user clicks back or refreshes the page

Sorry I have posted this question and I googled it alot still Im unable to solve this
I have a php page that has a form and when user clicks refresh or F5 it creates duplicate values in the database and also a message is alerted to the user, indicating resubmitting may insert duplicate values in database.My boss dont want that alert box of the browser to user and also insertion of duplicate values into the database
I know its header(). I read lot of header() in php manual and also server_name functions but still I tried in many ways putting in the top but cant solve it. its very important. can anyone please help me with a sample of code explaining the way to do.any help is greatly appreciated.
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
</form>
demo.php
<?php
$firstname = $_POST['fname'];
?>
Tell me what should i add in the demo.php page to stop it from submitting the form again and again and also if user clicks back button on the browser it should not direct to the previous page , it should still redirect to current page.
So if user clicks refresh or back button it should redirect to current page only and should not insert any duplicate values and also alert box should be disabled.Please explain me what to do here, im in deep help.Thanks
There's lots of things wrong with your code, and lots of ways to mitigate the impact.
First, why are you creating duplicate entries?
In addition to the problem of bad data is also implies that your site is vulnerable to CSRF. Go read up on how to prevent CSRF with single-use tokens.
If you've got performance problems with your site, then users will often click on the submit button multiple times. While addressing the duplicate submission problem on the database, use javascript to disable the submit links on the page and provide visual feedback that the page is doing something.
Redirects are not the way to solve the problem.
My boss dont want that alert box of the browser
Are you talking about the duplicate post alert? While you can get around this using PRG, that creates other problems.
You must post a unique id (session_id) and save it in the database.
When your registration, test if the session_id is already present. If so, send a message to THE USER. "You have already post out this form"
The code:
<?php session_start; ?>
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
<input type="hidden" name="session_id" value="<?php echo session_id();?>">
</form>
demo.php
<?php
//test session_id in database
$session_id = session_id();
mysql_connect('localhost','xxx','xxx');
mysql_select_db('xxx');
$return = mysql_query("SELECT COUNT(*) AS nb_data FROM TABLENAME WHERE session_id='".session_id()."'");
$data = mysql_fetch_assoc($return);
if ($data['nb_data'] == 0){
echo 'Your message';
}
else{
$firstname = $_POST['fname'];
//.....
header('location:xxx.php')?
}
?>
I would use php header function to replace the current location so if the user clicks refresh, it won't repost the information and a session to store the posted value and check for resubmissions.
demo.php
<?php
session_start();
if($_POST)
{
if(!isset($_SESSION[fname]))
{
//database queries here
}
$_SESSION[fname] = $_POST['fname'];
header('location:demo.php', true); //true replaces the current location
}elseif(!issset($_SESSION[fname])){
header('location:form.php');
}
$firstname = $_SESSION[fname];
?>
form.php
<form method="post" action"demo.php">
<input name="fname" type="text">
<input type="submit" value="submit">
</form>
You need ON DUPLICATE KEY , this will update the record instead of creating a copy of it :
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
so it wouldn't matter if they hit refresh or resubmit, if the record existed already it would just get updated.
The solution will be to redirect the page after database operations like insert, update and delete
pageName: test.php
if(isset($_REQUEST['deleteBtn']))
{
$emp_id=$_REQUEST['emp_id'];
$count=mysql_query("delete from employees where emp_id=$emp_id");
header("location:test.php");
}
This way if you click F5 or back button the form data will not get posted again.
What you want is to embed a session id in your form when you create it, and to track that session id on the server. Then, when the form is submitted and you are processing the form on the server, if the form was submitted more than once, you can overwrite the first submission in your database, or respond with an error message, or whatever. (Show the popup only on the first submission, whatever.)
An easy way to do this is to generate a session id, send it as a hidden field in the form, and when the form is submitted store the session id in your database with the constraint that the session id be unique.

php secure comment logic?

Ok, this might be obvious but its not clicking quite yet. I am creating a forum/blog esque app.
I grab the posts from the database rather securely but commenting is beginning to be a little more difficult. (I could just be paranoid, right?).
How do I add a comment without exposing the id of the parent message? (like in a hidden form field or query string, or something).
I guess I am a bit paranoid that someone might go into the code with firebug or something and change the hidden form field value to something else before submitting. I guess I would have to make sure the user has permission to comment to that particular post/category?
Things to note :
The user is already logged in.
Its not a public post
I would recommend that you setup your database like so:
Comments
---------
id
encodedID
authorID
parentID
message
Then, for the form field have two hidden values, one will be the encodedID, and the second will be a hash that you make. I would recommend the hash to be:
<?php
$hash = sha1(md5($encodedID . $userID . $_SERVER['REMOTE_ADDR'] . "abc1234"));
?>
Then, when the user submits the form, validate that the hash is valid for the specific encodedID and user. Here is a brief code write up:
<?php
if(isset($_POST['submit']))
{
//Get the variables and all and sanitize the input of 'message'
if(sha1(md5($_POST['value1']. $userID . $_SERVER['REMOTE_ADDR'] . "abc1234")) == $_POST['value2'])
{
//User is valid.
}
else
{
//Invalid user.
//Document this.
}
}
$value1 = $encodedID; //Grab this from your database
$value2 = sha1(md5($value1 . $userID . $_SERVER['REMOTE_ADDR'] . "abc1234"));
?>
<form method="post" action="comment.php">
<input type="text" name="message" />
<input type="hidden" name="value1" value="<?php echo $value1; ?>" />
<input type="hidden" name="value2" value="<?php echo $value2; ?>" />
<input type="submit" name="submit" value="Comment" />
</form>
Edit: Just a small tip, but I would recommend that you change value1 and value2 to something abstract, don't call it encodedID or anything like that, just so that it confuses any users that will attempt to try and break it.
And yes md5 and sha1 are not completely secure, but for this case it will work since you want to be able to process the comments fast and efficiently.
That might be an overkill but if you really want to hide the post_id of the current message then you should consider using session. So instead of using something like this on your form:
<form action="/postcomment.php" method="post" >
<input name="post_id" type="hidden" value="123" />
<textarea name="message"></textarea>
</form>
Reduce it to something like this:
<?php $_SESSION['post_id'] = '123'; ?>
<form action="/postcomment.php" method="post" >
<textarea name="message"></textarea>
</form>
Of course this is "yucky" coding but at least you get the idea.
Oh, don't forget to validate EVERYTHING on postcomment.php. Also escape ALL string input values and make sure all numeric inouts are numbers indeed (multiply them by one?).
[EDIT: Due to insistent public demand, may I, if you please, amend the aforementioned:]
Instead of:
<?php $_SESSION['post_id'] = '123'; ?>
Generate a form id:
<?php $_SESSION['form_id'] = $_SESSION['user_id'].'_'.md5(time()); ?>
Then generate the unique post_id:
<?php $_SESSION[$_SESSION['form_id'].'_post_id'] = '123'; ?>
After submitting get the post_id:
<?php $post_id = $_SESSION[$_SESSION['form_id'].'_post_id']; ?>
you could assign the form an "id" as a hidden field and create a database table to track form ids and their associated post ids, that way when the form gets submitted you could check the post id in the db without ever sending it to the client based on the form id that is returned with the post
You're asking the wrong question here: instead of being concerned about the user getting some internal ID that means nothing outside your application, your primary concern should be about keeping them from doing anything unpleasant with it.
Imagine I just started sending POST requests to add a comment for every ID between 1 and 10,000. I'm sure to hit a real post sooner or later.
Rule #1 about writing secure web applications: Don't trust the user.
In other words, yes, you should check to make sure that they have permission to comment when you receive the results back from the from.

Using javascript and $_SESSION's to record wanted user information over pagination

What I have so far is a paginated page, showing all users in a database system. Each page shows 30 users and has a checkbox next to each user, what I need is a way for users to select and deselect these users and for these selections to propagate through, so if the user goes back to page 1 from page 2, all users from page 1 will still be checked.
I also need a way to record this information, so that once the user has looked at all the pages and clicks a submit form all checked users information can be processed. I am thinking of using javascript to record the information and php sessions to store it, but with the way I am trying now, when a user clicks a checkbox, it is not ticked.
Does anyone have a better way of doing this/see how I can fix this problem?
Thanks.
<script type="text/javascript">
function log_export($str) {
document.check.data.value = $str;
document.check.submit();
}
</script>
<?php
if(isset($_POST['data'])) {
echo $_POST['data'];
}
?>
<form name="check" method = "post" action = "">
<input type="hidden" name="data">
<input type="checkbox" name="A" onclick="log_export('1')" />
<input type="checkbox" name="B" onclick="log_export('2')" />
<input type="checkbox" name="C" onclick="log_export('3')" />
</form>
Few ways you could do this, but I'd avoid using javascript to do it. You could use an array in your $_SESSION to keep the list across pages.
<form name="check" method = "post" action = "">
<input type="checkbox" name="person[A]" />
</form>
(note: The form elements are named person[A], person[B]...etc, so they can be accessed as an array in php and make your life easier.)
Then in the php you can store this in the session...
$_SESSION['saved_list'] = $_REQUEST['person'];
This way the session variable saved_list will contain the array person with all the checked boxes in it. You'll need to be careful not to overwrite the array each time however, so adding...
$_REQUEST['person'] = array_merge($_SESSION['saved_list'], $_REQUEST['person']);
...before this should keep them (if I'm remembering my merge functions correctly).
Alternatively, you could just use html to save the checkboxes already ticked. When page 2 receives the results from page 1, it could print them out as hidden elements at the end of the page 2 form. This way they can exist across pages, however this could become a bit unwieldy with 30 names a page.
I'd suggest storing it in a php session array, this shouldnt really involve using Javascript, it just over-complicates matters.
Why you don't change your form method to GET and make the pagination link so it contains every parameters passed to the form and the page number. I think it make everything more simple to handle that case with parameters passed on the URL against posted one.
you can create those links like this:
for ($i =0; $i < $max_page; $i++){
echo "{$_SERVER['REQUEST_URI']}?$_SERVER['QUERY_STRING']&p={$i}";
and you just have to change your backend to use $_GET instead of $_POST.

Very quick, easy, webpage with increment/decrement

I'm looking for any direction on a really quick and dirty webpage. I'm going to have two static items, say person A and person B. I would like to click a (+) or (-) button next to each of them which then increments or decrements an integer that's displayed relative to each person.
Anyone having a quick tut or anything would be useful.
Aside from this, how hard would it be to keep a viewable log of each time the value was altered either incremented or decremented, would it be easy to add in date/time to that?
Edit
Alright, concerning mysql. I have a db already setup from a previous wordpress installation. I'm going to create a new tables named 'points', should this have 2 fields? One for a person A and one for a person B?
Since you want it to remember the value between sessions (ie- if I incremented the counter, left the website, and came back, I expect it to still be incremented) you need to store the value server-side. Databases are the best recommendation for this.
If you're planning to use PHP (which I assume from the tags), then MySQL is one of the easiest databases to implement. If you already have a MySQL database set up at your host, then this will be easy. If not, how to set up a MySQL database will be another question you need to ask.
Since you want quick and dirty the best method would be a form. Either POST or GET (preferably GET if you want people to send a "vote up this image" link, preferably POST if you don't want such links to be possible). This is easy, but it also requires reloading the page which is why modern voting systems use AJAX calls (javascript).
Your HTML form would look something like this:
<!-- Person A goes here -->
This person has a score of <!-- We'll do this soon -->.
<form method="get" <!-- or post --> action="vote.php">
<input type="submit" name="submit_button" value="Vote Up!" />
<input type="submit" name="submit_button" value="Vote Down =(" />
<input type="hidden" name="person" value="A" />
</form>
<!-- Similar for person B -->
Note that <!-- --> is the syntax for an HTML comment (these will be removed in the final website)
In vote.php you would need to first see if the form was submitted, then see WHICH submit button was pressed (vote up or down), then see which person it applies to. Then we do our database entry.
<?php
if(isset($_GET['submit_button'])){
// They submit the form
$add = ($_GET['submit_button'] == 'Vote Up!') ? 1 : -1;
$person = $_GET['person'];
$link = mysql_connect('localhost', 'user', 'password');
mysql_select_db('database', $link);
mysql_query("UPDATE table SET value=value+$add WHERE person=$person");
} else {
die("You didn't submit the form =(");
}
?>
Mind you this is a REALLY dirty method (there is no parsing of the query and no checks made. This is very susceptible to an SQL injection. Do NOT use this in a database with important information. In fact- probably don't use this at all without a few changes =) )
Now then, this basically takes the table table, finds the entry where person equals whatever person was selected (chosen by which form was used to submit), then adds either +1 or -1 to value. You can change any of these variable names in your own table. The next step: reading the value to display on the previous page. Remember that before I just had the comment <!-- we'll do this soon -->. We'll get to that now.
In the beginning of your first page you want to read the database. This means your first page must also be PHP.
<?php
$link = mysql_connect('localhost', 'user', 'password');
mysql_select_db('database', $link);
$result = mysql_query("SELECT value FROM table WHERE person=A");
...
Now you have a MySQL resource, but you need the value out of it.
...
$row = mysql_fetch_row($result);
...
And now we display it with the information.
<!-- Person A goes here -->
This person has a score of <?php echo $row[0]; ?>.
<form method="get" <!-- or post --> action="vote.php">
<input type="submit" name="submit_button" value="Vote Up!" />
<input type="submit" name="submit_button" value="Vote Down =(" />
<input type="hidden" name="person" value="A" />
</form>
Then you repeat for person B. This is really the dirtiest method since it involves one call to the database per person. Ideally you'd grab all values you want in a single call and then iterate over the returned resource and determine who was who. Or, if you really wanted to be fancy, you could already know who was who by using SORT ASC =)
Like I said, though, this is the quickest, easiest, and dirtiest method to do what you want using PHP and MySQL.
Anyway I'd go for the database storing of person data and increment by id .
This is the flow for it :
Create mysql or mysqli database "person", create table "rates" id - autoincrement
rate will be integer.
Create php file with database connection and the functions related to it.
you can use same file to create increment function, when row is the result from the integer relative to this entry :
$rate = $row['rate'];
function incvar(){
global $rate;
if(isset($rate) || $rate>0){
return $rate++;
}
}
function decvar(){
global $rate;
if(isset($rate) || $rate>0){
return $rate--;
}
}
Now create query updating existing fields with results from those functions.
Ideally is to create ajax request onclick to this file to increase and decrease the integer. For fast execution use jquery.

Categories