Here, I have made validation for checkbox.
First when I select on submit button, it shows validation error.
After that when I click on "selectall" button, it goes in update query that is on submit button.
That mean, $_POST is setted.
I have unset that submit button for that, although it is going in update query through "selectall" button.
Why this is happening?
if(!empty($_SESSION['id']) && isset($_POST['processorder']))
{
echo "hello";exit;
$chk = $_SESSION['id'];
$query="update order_details set process_order='1' where id IN(".implode(',',$chk).")";
//mysql_query($query) or die(mysql_error());
unset($_SESSION['id']);
unset($_SESSION['on']);
$_SESSION['flash']['success'] = 'Order processed successfully.';
header('Location: '.$_SERVER['REQUEST_URI']);
die();
}
if(empty($_SESSION['id']) && $_POST['processorder'])
{
print_r($_POST);
$error = "Please select an Order(s)..!!";
unset($_POST['processorder']);
echo "<br>";
print_r($_POST);
}
<input type="button" name="selectpage" value="Select All Page" onclick="selectall()"/>
<input type="submit" id="processorder" name="processorder" value="Process Order" class="submit-green"/>
<input type="checkbox" name="id[]">
If you would like to unset all $_POST values you shouldn't just unset $_POST['processorder'].
if (isset($_SESSION['id']) && $_SERVER['REQUEST_METHOD'] == 'POST') {
// to unset processorder
unset($_POST['processorder']);
var_dump($_POST);
// To unset all $_POST values
unset($_POST);
var_dump($_POST); // Will return bool(false)
}
Since you've unset($_SESSION['id']);, if(empty($_SESSION['id'])) will return TRUE.
This happens because if(empty(unset($var))) will always return TRUE.
Related
For some reason or another, this sql is executing and outputting:
successfully added the following paypal button to this product... But it's not updating. I'd appreciate any help on this.
if(isset($_REQUEST['submitedform'])) {
if ($_POST['paypal']) {
$paypal=$_POST['paypal'];
$id = $_GET['id'];
$query = "UPDATE `video_info` SET paypal_button_html='".$paypal
."' WHERE id='".mysql_real_escape_string($id) ."'";
mysql_query($query) or die(mysql_error());
echo "successfully added the following paypal button to this product:
<br /><br />
{$paypal}";
}
}
?>
<?
if ($_GET['id']) {
?>
<h1>Add PayPal Button In for this product:</h1>
<form action="add_paypal.php" method="POST">
*Paypal button html: <br><textarea rows="2" cols="20" name="paypal"></textarea><br>
<input type="hidden" name="submitedform" value="true" />
<input type="submit" value="Add paypal button in for this product">
</form>
<?
} else {
echo "You can not come to this page manually.";
}
?>
A few problems:
You were not being consistent in sanitising your Database Input
You did not have clear validation rules
Your form was not setting the $_GET['id'] field (so the database submission was always failing)
Amended code:
<?php
// Init an Array to hold any error messages
$errors = array();
if( isset( $_REQUEST['submitedform'] ) ){
// Validate the required fields
if( !isset( $_POST['paypal'] ) || $_POST['paypal']=='' )
$errors['paypal'] = 'No value for "paypal"';
if( !isset( $_GET['id'] ) || !is_numeric( $_GET['id'] ) )
$errors['id'] = 'No value for "id"';
// If Validation was successful
if( !$errors ){
// Prepare the Variables for Database Usage
$paypal = mysql_real_escape_string( $_POST['paypal'] );
$id = (int) $_GET['id'];
// Template and Complete the SQL Query
$sqlTpl = 'UPDATE `video_info` SET paypal_button_html="%s" WHERE `id` = %s';
$sqlStr = sprintf( $sqlTpl , $paypal , $id );
// Submit the Query
if( !mysql_query( $sqlStr ) ){
// Something went wrong
$errors[] = 'An error occured when submitting the data to the database';
}else{
// Submitted OK
echo 'Successfully added the following paypal button to this product:'.$paypal;
}
}
}
// Check for any errors
if( $errors ){
// Show errors to user
echo 'The following errors occurred:';
echo '<ul><li>'.implode( '</li><li>' , $errors ).'</li></ul>';
}
?>
<?
if( isset( $_GET['id'] ) && is_int( $_GET['id'] ) ){
?>
<h1>Add PayPal Button In for this product:</h1>
<form action="add_paypal.php?id=<?php echo $_GET['id']; ?>" method="POST">
*Paypal button html: <br><textarea rows="2" cols="20" name="paypal"></textarea><br>
<input type="hidden" name="submitedform" value="true" />
<input type="submit" value="Add paypal button in for this product">
</form>
<?
} else {
echo "You can not come to this page manually.";
}
?>
This code...
Includes the id in the form's action URL
Checks for the submission
Validates the submitted values
Creates the Database Query
Submits the Query
Checks the Query worked OK
AMENDED: Replaced is_int() with is_numeric() as, after RTFMing, I found that a string, comprised of only digits, will apparently return false if tested with is_int().
UPDATE
Please, use $_REQUEST OR $_GET OR $_POST but not all 3 of them.
Also, why don't you mysql_real_escape_string the variable $_POST['paypal'] ?
You mix $_GET and $_POST variables. You should use either GET or POST, but not both. If this is a post request, change $_GET['id'] to $_POST['id'].
In this case, the update doesn't fail because of where id = ''. This doesn't update anything, because there's no id with an empty string. But it also doesn't fail, since it is a valid update statement.
I have a script that I'm using that when the user enters a code I want it to add to the total in the database, however nothing is happening.
This is my code so far:
$err = array();
if (isset($_POST['doSubmit4']) === true ) // Was if ($_POST['access']=='submit')
{
$code = mysql_real_escape_string($_POST['access-key']); // Was $data['access-key']
$result = mysql_query("SELECT `akid`,`key`,`total_access` FROM access_keys WHERE id='$_SESSION[user_id]' AND type='1'") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the key exists.
if ( $num > 0 ) {
list($akid,$key,$total_access) = mysql_fetch_row($result);
if ($code == $key) {
if(empty($err)){
$total_access++;
mysql_query("update access_keys set total_access='$total_access' where akid='$akid'") or die(mysql_error());
header("Location: ./");
}
} else {
$err[] = "Invalid Access Key. Please try again with correct access key.";
}
} else {
$err[] = "Error - Invalid Access Key. No access exists for your user ID.";
}
}
I'm wanting it to add to the Total Access field each time the user enters the correct code, but it's not working.
This is my form code:
<form name="postAccess" id="postAccess" method="post" action="access.php">
<input type="password" name="access-key" id="access-key" style="background-color:black;color:white;" size="40" /><br/>
<input name="doSubmit4" type="submit" id="doSubmit4" value="submit">
</form>
It might be your parent if brackets.
Try:
if (isset($_POST['access']) === true )
instead of
if ( $_POST['access']=='submit' )
If that doesn't seem to do it, do some debugging.
Throw some echo statements in those if brackets to see what conditions are true and what are not.
EDIT:
I just realized another problem.
Your form action is invalid. This should be the path to the page you are posting the data to. So:
Instead of:
<form name="access" id="access" method="post" action="access">
You should have:
<form name="access" id="access" method="post" action="your-php-path-here.php">
Notice how action = "your-php-path-here.php" in the above code.
i have a crazy problem that i just can't figure out. my form has two fields and a submit button. when i submit the vars get passed into $_POST just fine...
print('<div class=error>');
print_r($_POST);
print('</div>');
that gives me the two fields with the expected values along with the value of the submit button.
HOWEVER! when i add the following line of code so i can process based on the submit button, it clears all of the data. the post array shows up empty.
if ($_POST['submit'] == 'Submit') {
that clears the data. if i change the value from 'Submit' to anything else, the vars still show up in $_POST, they just get cleared when i try to check them.
any ideas what i'm doing wrong here?
here's the form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<?
if (isset($msg)) {
echo "$msg";
}
?>
<input type=text name='email'><br>
<br><input type=password name='password'>
<br>
<input type="submit" name="submit" value=Submit>
</form>
and here's the processing code:
if ($_POST['submit'] == 'Submit') {
echo "<div class=error>made it here</div>";
$u = $_POST['email'];
$p = $_POST['password'];
$auth = mysql_query("Select * from member where email='$u' and password='$p'");
$auth = mysql_fetch_array($auth);
if ($auth) {
$pid = $auth[id];
echo "aa";
sess_register("sess_msg");
$sess_msg = null;
global $auth, $pid;
}
}
if i change the value when i check to see if the submit button has a value to something other than the actual value of the submit button, which is 'Submit' - it clears all variables sent to $_POST
If you want to check which submit button was clicked, you just have to look for its name as a key in the array $_POST.
So you should do:
if (array_key_exists('submit', $_POST)) {
// your code
}
Little advice: you'd better escape your $_POST data before putting it into a query!
Check this out: http://php.net/manual/en/function.mysql-real-escape-string.php
From your post, it doesn't look your code should be emptying the $_POST array. The only thing that I can think of at the moment is that maybe in the code you actually only put one '=' sign.
var_dump( $_POST );
if ( isset( $_POST['submit'] ) ) {
var_dump( $_POST );
echo "<div class=error>made it here</div>";
$u = $_POST['email'];
$p = $_POST['password'];
$auth = mysql_query("Select * from member where email='$u' and password='$p'");
$auth = mysql_fetch_array($auth);
if ($auth) {
$pid = $auth[id];
echo "aa";
sess_register("sess_msg");
$sess_msg = null;
global $auth, $pid;
}
}
var_dump( $_POST );
I've created a test form that uses IF.. ELSE to validate data in a simple form. This works ok and any validation messages or errors are posted to the same page (userform.php) to inform the user of success or otherwise.
What I want to do now is take the user to a different page on successful completion of the form. Here's my code so far:
<?php
if (isset($_POST['email'], $_POST['password'])) {
$errors = array ();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form";
}
if (empty($email)) {
$errors [] = "You must enter an email address";
}
if (empty($password)) {
$errors [] = "You must enter a password";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
}
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
$result = "userform.php";
}
} else {
$result = "confirm.php";
}
?>
<form action="<?php echo $result ?>" method="post">
The idea is that the users success or otherwise in completing the form changes the $result variable which is used in the form action. The above code doesn't work, so how would I do it?
Is it even possible?
instead of "form action=" at the bottom:
<?php
include($result);
?>
As I understand it you want it to work like so:
User fills form
User submits form
Form submission goes to userform.php
If all values validate, continue to confirm.php
If not, return to userform.php
If that's the case, I don't think you want to change the form action: that would require that the user re-submit the form. Instead, use a HTTP redirect to send them to confirm.php:
header("Location: confirm.php");
... or if you wanna be really by-the-book about it:
header("Status: 303 See Other");
header("Location: http://exampel.com/confirm.php"); // according to the protocol,
// `Location` headers should be full URLs
<?php
/* ... */
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
}
?>
<form action="userform.php" method="post">
<?php
} else {
header("Location: confirm.php");
// if you need to pass additional information to confirm.php, use a query string:
// header("Location: confirm.php?var1=".$var1);
}
?>
The way you're doing it now, will redirect the user to confirm.php if they submit the form for a second time. You could change your code to this:
} else {
// $result = "confirm.php";
header("Location: confirm.php");
exit();
}
That way, if everything has been entered, the user will be redirected to confirm.php. But what do you do with the variables if everything is allright? They won't be taken to the new page.
} else {
$result = confirm.php;
foreach($_POST as $key => $val){
$input.="<input type='hidden' name='$key' value='$val' />";
}
$form = "<form method='post' name='confirm' action='confirm.php'>".$input."</form>";
$script = "<script type='text/javascript'>document.confirm.submit();</script>";
echo $form.$script;
}
empty ($errors)
will ALWAYS return empty. That's why you always get:
$result = 'confirm.php';
Check return values here
Also, I don't think you can do this easily. Instead, why don't you just create a check.php or whatever to check the variables/check for errors, etc. Then do whatever you want (redirect back to the form-filling page or proceeding to confirm.php page.
The whole idea is wrong. You have to fix 2 issues in your code.
1. A major one. Learn to properly indent nested code blocks!
It's impossible to read such an ugly mass with no indents.
2. A minor one.
I see no use of confirmation page here. What are you gonna do on that page? And from where you're going to get form values?
It seems you have to either use just simple Javascript code to show a confirmation or store entered data into session
And, I have to say, that show a confirmation page for simply a feedback form is quite uncommon practice.
So, I think you really need only one form action and only thing to ccare is properly filled form
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
$errors = array();
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form. All fields required.";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
if (!$errors) {
// do whatever you wish to this data
// and then redirect to whatever address again
// the current one is a default
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['fiestname'] = $form['lasttname'] = $form['email'] = $form['password'] = '';
}
include 'form.tpl.php';
?>
while in the form.tpl.php file you have your form fields, entered values and conditional output of error messages
<? if ($errors): ?>
<? foreach($errors as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form method="POST">
<input type="text" name="firstname" value=<?=$form['firstname']>
... and so on
I have a very simple PHP form, which shows a checkbox, and will store if it is checked or not in a database. This works for the initial inserting, but not for updating. I have tested cases where $saleid equals $pk and it does not enter the if branch to update...why?
<?php
error_reporting(E_ALL);
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
if (isset($_POST["cmd"]))
$cmd = $_POST["cmd"];
else die("Invalid URL");
if (isset($_GET["pk"])) { $pk = $_GET["pk"]; }
$checkfield = "";
$checkboxes = (isset($_POST['checkboxes'])? $_POST['checkboxes'] : array());
if (in_array('field', $checkboxes)) $checkfield = 'checked';
$con = mysqli_connect("localhost","user","", "db");
if (!$con) { echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error(); exit; }
$con->set_charset("utf8");
$getformdata = $con->query("select saleid, field from STATUS where saleid = '$pk'");
$saleid = "";
while ($row = mysqli_fetch_assoc($getformdata)) {
$saleid = $row['saleid'];
$checkfield = $row['field'];
}
if($cmd=="submitinfo") {
if ($saleid == null) {
$statusQuery = "INSERT INTO STATUS VALUES (?, ?)";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("sssssssssssss", $pk, $checkfield);
$statusInfo->execute();
$statusInfo->close();
} else {
print_r($con->error);
}
} else if ($saleid == $pk) {
$blah = "what";
$statusQuery = "UPDATE STATUS SET field = ? WHERE saleid = ?";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("ss", $checkfield, $pk);
$statusInfo->execute();
$statusInfo->close();
} else {
print_r($con->error);
}
}
}
if($cmd=="EditStatusData") {
echo "<form name=\"statusForm\" action=\"test.php?pk=".$pk."\" method=\"post\" enctype=\"multipart/form-data\">
<h1>Editing information for Auction No: ".$pk."</h1>
<input type=\"checkbox\" name=\"checkboxes[]\" value=\"field\" ".$checkfield." />
<label for=\"field\">Test</label>
<br />
<input type=\"hidden\" name=\"cmd\" value=\"submitinfo\" />
<input name=\"Submit\" type=\"submit\" value=\"submit\" />
</form>";
}
?>
well i created a table and ran your code and it works fine for me
the reason why it doesn't "look" like update is working, is because you are reading
$saleid and $checkfield from the database then building an update statement that puts the same two values back into the database
which probably isn't what you are wanting to do
this line here sets $checkfield to 'checked',
if (in_array('field', $checkboxes)) $checkfield = 'checked';
then you set $checkfield from the database (overwriting the value 'checked' )
while ($row = mysqli_fetch_assoc($getformdata)) {
$saleid = $row['saleid'];
$checkfield = $row['field'];
then you write the original value of checkfield back to the database
$statusInfo->bind_param("ss", $checkfield, $pk);
not sure if you can mix GET and POST type requests
maybe change this so that pk is passed back as a hidden field ?
echo "<form name=\"statusForm\" action=\"test.php?pk=".$pk."\" method=\"post\" enctype=\"multipart/form-data\">
eg, sort of like this
echo "<form name=\"statusForm\" action=\"test.php\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"hidden\" name=\"pk\" value=\"".$pk."\">
Here is what your HTML should look like:
<form id="aform" action="thisform.php" method="post">
<input type="checkbox" name="agree" value="yes" />
<input type="hidden" name="secret" value="shhh" />
<input type="submit" value="do it" />
</form>
With the above if you do:
print_r($_POST);
you will get an array that either has [agree] => 'yes' or nothing, depending on if they check the box, so no need to put the array brackets unless you have tons of boxes.
As for the SQL part, I suggest making the column a single integer type, where it can have either a 0 or 1. 0 for unchecked, 1 for checked. For the insert you would do something like:
$check_value = ($_POST['agree'] == 'yes') ? 1 : 0;
$secret_stuff = $_POST['secret'];
mysqli_query("Insert INTO sales_table (secret_column, agree_column)
VALUES ('$secret_stuff', '$check_value')");
That will get your checkbox into the table. To get it out, you should go with:
$results = mysqli_query("SELECT * from sales_table where secret_column = $secret_stuff")
while($row = mysqli_fetch_assoc($results)) {
$checked = ($row['agree_column'] == 1) ? "checked=\"checked\"" : "";
$secret_stuff = $row['secret_column];
}
?>
<form action=blah method=post id=blah>
<input type="checkbox" name="agree" value="yes" <?php echo $checked;?> />
</form>
Sorry, lost steam at the end. But that covers the front end and back end. Use a 1/0 switch, and just set some variable like $checked to the "checked='checked'" if it's a 1.
You're not setting the $pk variable unless isset($_GET["pk"]), yet you're still using it later in the query. This isn't a good idea, since depending on other circumstances, this can lead to bugs. What you want your logic to look like is this:
if pk is not set in form
insert new record
deal with error if insert failed
else
update existing record
check update count and deal with error if 0 records were updated
(perhaps by doing an insert of the missing record)
end
Just as a side note, it looks like the mysql REPLACE function would come in handy for you.
Also, when a checkbox is not checked, the value can be a tricky thing. I have written a function that sets the value to one, if the posted value is set, and zero if not...
function checkbox_value($name) {
return (isset($_POST[$name]) ? 1 : 0);
}
You can run your posted checkbox value throught that query and always get a one or a zero.