PHP IF statement not working with _POST array - php

Having trouble with PHP (version is 5.6.27). My problem is I'm never getting into the IF loop, because the IF test fails, I assume because it's an array. I've tried using isset as well, to no avail.
if($_POST['product_new_quantity'] ){
foreach($_POST['product_new_quantity'] as $id => $new_quantity) {
if ($_POST['product_new_quantity'][$id] != $_POST['product_old_quantity'][$id]) {
// update the database with new value
}
}
}
Example data from the form looks like:
// BOF HTML FORM DATA - Formatted to display here.
// Yes I know It's missing the <> chars!
input type="hidden" name="product_old_quantity[62]" value="22"
input type="hidden" name="product_old_quantity[72]" value="11"
input type="hidden" name="product_old_quantity[3841]" value="64"
input type="text" name="product_new_quantity[62]" value="16"
input type="text" name="product_new_quantity[72]" value="15"
input type="text" name="product_new_quantity[3841]" value="58"
// EOF HTML FORM DATA
This apparently worked before on some prior version of PHP, but isn't anymore... and I REALLY don't want to have to refactor the entire report because these IF statements aren't working.

pleas check you have set form method post. => method="post"

Related

Submit form to action php file

I have a form where when the user clicks submit, I need a php file to be ran. below is the form and the php file.
<form action="php_scripts/test.php" method="POST">
<input name="feature" type = "text" placeholder="Feature" />
<input name="feature2" type = "text" placeholder="Feature2" />
<input type="submit" value = "submit"/>
</form>
test.php
<?php
if( isset($_GET['submit']) )
{
$feature = $_POST['feature'];
// do stuff (will send data to database)
}
?>
The problem I am having is that when I press Submit on the form,
if( isset($_GET['submit']) )
Always returns false.
Can anyone explain why that is? Have I totally misunderstood how to implement form sending data to php scripts?
Apologies if I have made any syntax errors and many thanks for any help you can give.
There are a few things wrong with your code.
You're mixing GET with POST methods. Plus, add values to your inputs and your submit button isn't named, which you're trying to use as a conditional statement for.
HTML
<form action="php_scripts/test.php" method="POST">
<input name="feature" value="feature" type = "text" placeholder="Feature" />
<input name="feature2" value="feature2" type = "text" placeholder="Feature2" />
<input type="submit" name="submit" value = "submit"/>
</form>
PHP
<?php
if( isset($_POST['submit']) )
{
$feature = $_POST['feature'];
$feature2 = $_POST['feature2'];
// do stuff (will send data to database)
}
?>
Sidenote: You could/should also check against empty values.
if(isset($_POST['submit'])
&& !empty($_POST['feature'])
&& !empty($_POST['feature2']) ) {...}
Footnotes:
Seeing that you're intending on sending to DB:
I hope you plan on using mysqli with prepared statements, or PDO with prepared statements.
A couple of things:
you're using $_GET instead of $_POST
isset($_POST['submit']) is not a good check, not every browser will send the submit button in its request. (Apart from the fact that you haven't even named the submit button, so it wouldn't come through in any browser, as it stands now.)
it's better to use:
Code:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
}
You missed to name the submit button. So no entry in the $_POST/$_REQUEST array is given. Depending on the php settings you might want to use array_key_exists() to check for an index in the array as isset might throws an error.

Need type="text" input fields to display previously-POST'd entries if errors occur

I've probably not explained what I"m trying to do in the title very well, so here goes:
I've got a HTML entry form, in a .php file. That entry form when submitted files a POST operation. That POST operation has code to check field input, similar to this:
<?php
...
if ($_POST["submitted"] == 1) {
//"submitted" is a hidden field with value '1' in the form
$isvalid = 1; // Inits to 1, changes to 0 if something fails checks.
$field1 = $_POST["field1"];
$field2 = $_POST["field2"];
...
/*
Checks for validation on each field go here,
but are not relevant to this question here.
*/
}
if ($isvalid == 1) {
// Send email
} else { ?>
<!-- Print form, and error msg. -->
...
<input name="field1" type="text" id="field1" size="32" class="stylingclass">
...
So the above is example code, but here's the real question: How can I get any of the text input fields in my form, when submitted and an error occurred, to automatically contain the previous values that were entered, so that the user can correct the entries accordingly, based on whatever constraints I've set?
You can set the value parameter using a basic ternary operator:
<input name="field1" type="text" id="field1" value="<?php echo isset($_POST["field1"]) ? $_POST["field1"] : ''; ?>" size="32" class="stylingclass">
Note that the ternary operator is used here to prevent an error if there is no index of the specified field in the $_POST array
Just add value="<?=$_POST['field1']?>" (assuming PHP 5.4, use <?php echo $_POST['field1'] ?> otherwise)

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

How to retrieve the checked state of a checkbox from a Html form and store it in a database?

i have a form field
<input type="checkbox" name="page" value=""/>
and corresponding field in mysql db is true and false, if someone click the checkbox i would like to send TRUE value to db via POST, how do i achieve it ?
You give the input any value you like:
<input type="checkbox" name="page" value="true"/>
Then, if the checkbox is checked, it will be a successful control and submitted.
<?php
if (isset($_POST['page']) && $_POST['page'] == 'true') {
// Then insert something into the database as normal
}
?>
If you want to set it when the checkbox is not ticked, then you will need an else to go with the if.
For a checkbox, the value attribute determines what the value will be if the item is checked. If it isn't checked, then no value will be submitted at all. You should therefore always specify the value attribute on a checkbox.
If you want the checkbox to default to checked, then you also need to specify the checked attribute.
<input type="checkbox" name="page" value="1" checked='checked' />
The Form:
<form action="/path/to/processing_script.php" method="POST">
<!--... Other Form Elements go here -->
<input type="text" name="color" />
<input type="checkbox" name="page" value="True"/>
<input type="submit" value="Send to Database" />
</form>
Processing script:
(processing_script.php)
<?php
// Check is 'True'?
if ($_POST['page'] != 'True')
{
$_POST['page'] = 'False';
}
$con=mysqli_connect("your-db-loc","your-db-username","your-db-pass","db-name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL Database: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO TableNameHere (True-false, Favorite Color)
VALUES ($_POST['page'], $_POST['color'])");
mysqli_close($con);
?>
This example I created add's 2 data types to a new row on the database.
Replace the text 'TableNameHere' with your db table name, should be in similar format to: 'prefix_colors_tble'
Replace the text "your-db-loc" with your databases location, usually 'localhost' for internal server, or could be a URL for live server.
Replace the text "your-db-username" the username used to login to mysql, must have sufficient privileges.
Replace the text "your-db-pass" the user's password
Replace the text "db-name" database name (not deemed important unless containing multiple databases)
Replace the text "True-false" & "Favourite Color" with your db table column headings as appropriate.
Good Luck! -p.s. I know this answer is a few years late, but I hope it can help somebody else. Send your appreciation to http://amazewebs.com/testimonial Thanks.
Collect the follows by reading $_POST after form submission, then write them to the database using mysql_query
the first thing you will have to do is to modify the current html code for checkbox and add something in the value field.
let say you set the value to 1.
The second thing is if you are posting the form, then you will have to process the form using a server side language like PHP,Perl, Java etc.
for e.g. in PHP you can get the catch what is sent for the page field using $_POST['page'].
Now you will have to do a bit of server side processing to see if the $_POST['page'] == '1' , then set $page = 'true';else set$page = 'false';
the you can insert the $page into the database by using the library functions of the language you are using.

Javascript mysql interface?

I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed

Categories