I'm building a form (fun) and obviously those can get tedious and as i sit here writing validation functions I'm wondering...
Say for example I have 3 fields*(name,lastname,age)*
The variables are
$fname = $_POST['name'];
$lname = $POST['lname'];
$age = $_POST['age'];
And say I want to check for empties, id
if(empty($fname) || empty($lname) || empty($age)){
//do something
}
Is there a way to make this more manageable? Because say that now, instead of 3 fields in the form, I have 100...it get quite unruly fast
So is there a way I can check en-mass ?
$required_fields = array("name", "address", "phone", "email");
foreach ($require_fields as $field) {
if (!strlen($_POST[$field])) {
echo "$field cannot be empty";
}
}
EDIT:
You Can get the $_POST array by
foreach ($_POST as $key => $name) {
$required_fields[] = "$key=$name";
}
If you want to check them all, do something along the lines of.
if(!empty($_POST)){
foreach($_POST as $key => $val){
if(empty($val)){
// An empty field exists. Your action here.
}
}
}
Although it's worth noting that if you have checkbox's on your page which aren't ticked, an empty $_POST entry won't get send back, it just won't exist at all.
So you'll need to check checkbox's with an if statement.
For example, the checkbox name is 'agree'
if(!isset($_POST['agree'])){
// Checkbox not ticked.
}
if(empty($_POST)){..}else{...} will give you result, depending on, If more than one value is set; or no value is set at-all. Sort of like True/False.
But, you must not include a value='' for the "Submit Button" itself, otherwise, it will give you a True result, all the time. Because the $_POST global, checks the value of the submit button too.
or, you can deduct one value from your query. Optionally you can debug values by var_dump($_POST)
If you want to check, "at-least one field is not empty" then,
if(count($_POST) !=0){
echo ' at least one value is set';}
else {echo 'no value is set';}
will check, if there is at-least, one item submitted.
btw. if you do
$fname = $_POST['name']
and the field isn't in the form you'll get
Notice: Undefined index...
better use
$fname = !empty($_POST['name']) ? $_POST['name'] : '';
Check each post key
if(isset($_POST) && count($_POST)!=0){
foreach($_POST as $key=>$val){
if(empty($key)){
/* do something */
}
}
}
Related
I have this update statement (PHP code):
$sql1="UPDATE `utilizatori` " .
"SET utilizator='$utilizator', parola='$parola1', nume='$nume', " .
"`prenume='$prenume', varsta='$varsta', localitate='$localitate'` ";
WHERE parola='".$_SESSION['parola']."'";
This will update some MySQL table fields via an html form. The user wants to change just his name for instance. He completes just name field, then he presses submit. The data is sent into the table with the UPDATE statement above.
The problem is that it also updates the table with blank values that user didn't complete. I don't want the blank values to be added.
How can I block the blank values to be sent into the table?
If you really wanted to do this in the update, you can change the set statement to something like:
set utilizator = (case when '$utilizator' <> '' then '$utilizator' else utilizator end),
. . .
This will use the previous value if the new one is blank.
You can also do this at the application level by just updating the fields that have changed.
And, you should use parameterized queries rather than directly substituting values into a string. That is another issue, though.
You can do two things to solve this issue. One is to preload the data in the form. So when the user change his name, the other fields are already loaded with the original information.
The second option is to create an update query based on the fields have a value.
Example of option 1:
<?php
//
//GET THE DATA FROM A SELECT QUERY HERE
//FOR EXAMPLE: $sql = "SELECT * FROM `utilizatori` WHERE parola='".$_SESSION['parola']."'";
//Put the data of the sql row in a variable e.g. $sqlRow.
?>
<!--Use variable in your form!-->
<form>
...
...
<input name="nume" value="<?=$sqlRow['nume']?>"/>
<input name="utilizator" value="<?=$sqlRow['utilizator']?>"/>
...
...
</form>
Example of option 2:
<?php
//Catch post data
if($_POST)
{
$updateString = "";
foreach($_POST as $inputField => $inputValue)
{
if($inputValue != "")
{
$updateString .= $inputField." = '".$utilizator."',";
}
}
//Strip last ,
$updateString = substr($updateString,0,-1);
if($updateString != "")
{
//Your query would be
$sql1 = "UPDATE `utilizatori` SET ".$updateString." WHERE parola='".$_SESSION['parola']."'";
}
}
?>
$updateClauseArr = Array();
foreach($_REQUEST as $key => $val){
if(is_numeric($val)){
$updateClauseArr[] = '$key = '.(int) $val;
}else{
$updateClauseArr[] = "$key = '".htmlentities($val,ENT_QUOTES,'UTF-8')."'";
}
}
if(sizeof($updateClauseArr) > 0){
$updateSet = implode(',' ,$updateClauseArr);
$sql1="UPDATE `utilizatori` SET ".$updateSet." WHERE parola='".$_SESSION['parola']."'";
}
See what field values have been submitted by the user. then iterate in a loop for the fields that have value to make variable to be concatenated to the update query.
I've got the following code which is something like a form search engine with multiple inputs where the results are kinda absolute concerning the number of characters etc(perfect match)
.
// build array of field names=============================================================================
$fields=array('user','customer','vessel','country',
'port','eta','service_station','type_of_service',
'case_reference','status');
// initialize empty array for WHERE clauses
$wheres=array();
// loop through field names, get POSTed values,
// and build array of WHERE clauses, excluding false values
foreach ($fields as $field) {
// get existing field value from POST, mark missing or empty value as FALSE
${$field} = isset($_POST[$field]) && trim($_POST[$field])!=''
? trim($_POST[$field]) : false;
// add to array of WHERE clauses only if value is not FALSE
if (${$field}) { $wheres[]="$field='".${$field}."'"; }
}
// build SELECT statement from WHERE clauses
$sql="SELECT * FROM jobs WHERE ".
(!empty($wheres) ? implode(" AND ",$wheres) : '1=1').
";";
What i want to do is add an input in the form
<label for="special">Special Search</label>
<input type="text" name="special" id="special_search">
where the user would be able to search in the case_reference field and get the results that match the first four characters. Also i would like this new input to work the same as the others as far as the AND or OR and TRUE or FALSE statements are concerned.
All help appreciated thank you in advance:)
UPDATE : Instead of rewriting the whole thing i came up with the following code at the begining of my previous :
$joker = $_POST['special'];
$joker1 = substr($joker1, 0, 4);
if(isset($_POST['case_reference']) && !empty($_POST['case_reference'])
&& empty($_POST['special'])) {
} else { $_POST['case_reference'] = $joker1; }
It is working for now but anyone can confirm that it would be okay in future??
From the SQL:
$sql="SELECT * FROM jobs WHERE ". (!empty($wheres) ? implode(" AND ",$wheres) : '1=1').";";
Just simply add a variable for special:
$special = $_POST['special']; // this will get the data from the textbox
then add it to the sql statement
$sql="SELECT * FROM jobs WHERE LIKE $special 'aaaa%' AND ". (!empty($wheres) ? implode(" AND ",$wheres) : '1=1').";";
Rewritten avoiding variable variable names, and using mysql_real_escape_string (although you should use mysqli or pdo):-
<?php
// build array of field names=============================================================================
$fields=array('user','customer','vessel','country',
'port','eta','service_station','type_of_service',
'case_reference','status');
// initialize empty array for WHERE clauses
$wheres = array('1=1');
// loop through field names, get POSTed values,
// and build array of WHERE clauses, excluding false values
foreach ($fields as $field)
{
// get existing field value from POST, mark missing or empty value as FALSE
if (isset($_POST[$field]) && trim($_POST[$field])!='')
{
$wheres[]="`$field`='".mysql_real_escape_string(trim($_POST[$field]))."'";
}
}
if (isset($_POST['special']) && trim($_POST['special'])!='')
{
$wheres[] = " case_reference' LIKE '".mysql_real_escape_string(trim($_POST['special']))."%'";
)
// build SELECT statement from WHERE clauses
$sql="SELECT * FROM jobs WHERE (".implode(" AND ",$wheres).") ;";
?>
I have 2 php pages. 1st php page is the following:
<?php
//code...
if(isset($_POST['value'])== true && empty($_POST['value']) == false){
echo"<a href='search_form_all_2.php'>See more results for </a>";
} ?>
the second page is the "search_form_all_2.php".
<?php
$value = mysql_real_escape_string($_POST['value']);
$name_and_surname = explode(" ", "$value ");
$name = $name_and_surname[0];
$surname = $name_and_surname[1];
$query = mysql_query(" SELECT `name`, `surname`, `email`, `user_id` FROM users
WHERE (surname LIKE '$name%' AND name LIKE '$surname%') OR (surname LIKE
'$surname%' AND name LIKE '$name%') ");
while($run = mysql_fetch_array($query)){
$surname = $run['surname'];
$name = $run['name'];
echo"$surname $name ";
}
?>
I want to make the $value in "search_form_all_2.php" to get the value of the first page that I have in if(isset($_POST['value'])== true && empty($_POST['value']) == false) of 1st page. How can I do this because when running "search_form_all_2.php" I get an erros message:Notice: Undefined index: value
You need to use GET in this case. POST values are only send when a form is submited.
if(isset($_POST['value'])== true && empty($_POST['value']) == false){
echo "<a href='search_form_all_2.php?value=".urlencode($_POST['value'])."'>See more results for </a>";
then on second page you retrieve the GET value
$value = mysql_real_escape_string($_GET['value']);
Be careful, GET values are visible to the user. They are part of a URL. Don't send confidential information.
Another way is to save the value in a COOKIE or in SESSION variable.
setcookie("TestCookie", $_POST['value']);
$value = $_COOKIE["TestCookie"];
BTW empty() always returns boolean value and it already checks if the variable is set, so you only need:
if(!empty($_POST['value'])
In your 1st page, you can pass an argument in the url... example:
echo "<a href='search_form_all_2.php?s=".urlencode($_POST['value'])."'>See more results for </a>";
Then, in your 2nd page, you can call the argument... example:
$value = mysql_real_escape_string($_GET['value']);
PS: You shouldn't be using mysql_* functions. Instead learn mysqli at the very least or PDO.
On search_form_all_2.php you can't access the data value because when you click a link, it is a GET request, not a POST request. I suggest you look up the differences.
However, if you use this to spit out the link:
echo"<a href='search_form_all_2.php?more={$_POST['value']}'>See more results for </a>";
You can then retrieve it with $_GET or $_REQUEST (if you want to be able to use GET or POST) on page 2:
$value = mysql_real_escape_string($_REQUEST['value']);
I have the following to generate a state drop down on a form:
$states = array('State', 'Alabama', 'Alaska', 'Arizona', 'Arkansas');
echo "<select name='choose_state'>\n";
foreach ($states as $key => $state)
{echo "<option value='$key'>$state</option>\n";}
echo "</select>";
How would I go about making sure a user
1) only selects one of the options in the array
2) doesn't select the default value? ([0]=> string(5) "State")
edit: validate in php, this is for a form collecting user information before posting to a db
I tried using in_array and got stuck trying to exclude the default value
I think you're missing some checks. You should never rely on what is exacly posted, and always perform thorough checking:
$chosen_state = null;
if (array_key_exists('choose_state', $_POST))
{
$choose_state = $_POST['choose_state'];
if (array_key_exists($choose_state, $states) && $choose_state > 0)
{
// Value does actually exist in array and is not item 0.
$chosen_state = $states[$chose_state]);
}
}
Following example assumes that you're storing the key provided for the select in the var $state_key...
try this:
$max = sizeof($states) - 1; // this is the number of possible values that you have, minus the default
if($state_key != 0 && $state_key > 0 && $state_key < $max)
{
// do whatever here, you've got good data at this point
}
This also assumes that your default value is always key #0 (first in the array), by the way.
Validating form submit in php:
When you submit form in php, Select input type returns selected value in post. So you can do something like:
$selectedindex = $_POST["choose_state"];
if($selectedindex == 0)
{
echo "Default item has been selected";
}
else{
echo "Other than default item has been selected ";
//you can do further validation here for selected item
//is in between 0 and 5 if you need to do so
}
I am having trouble getting a form to update the information passed from a check box. I was given this code.
$one = isset($_POST['one']) ? 'on' : 'off';
This works great as long as I call each check box separately. My problem is I have approximately 200 checkboxes in total.
Here is the code I am using to UPDATE with. Can anyone help me to figure out where to insert the code I was given into my present code? I've tried all sorts of variations.
if($_POST['submit']){
if(!empty($applicant_id)){
$sql = "UPDATE play SET ";
foreach($_POST as $key => $value){
if(($key != 'submit') && ($key != 'applicant_id')){
$sql .= $key. " = '$value',";
}
}
$sql = substr($sql, 0, -1);
$sql .= " WHERE ".$applicant_id." = $applicant_id";
$result = mysql_query($sql,$db) or die(mysql_error(). "<br />SQL: $sql");
}
}
The solution is to start with your known list of possible checkboxes in an array() or similar. Can I assume you generate the form with such a list? If not, you probably should. Then you can use a loop over the same data to check for the existence of each checkbox.
Some other hints:
isset($array[$key]) is not recommended. Although it will be reliable most of the time, it will fail if $array[$key] is null. The correct call is array_key_exists($key, $array).
When assembling string fragments for SQL, like you're doing, it is more elegant to do the following:
$sqlvalues = array();
foreach( $options as $field ) {
if( array_key_exists('checkbox_'.$field, $_POST) )
$sqlvalues[] = $field.' = \'on\'';
else
$sqlvalues[] = $field.' = \'off\'';
}
mysql_query('UPDATE '.$table.' SET '.implode(', ', $sqlvalues).' WHERE applicant_id = '.$applicant_id);
You may be running to HTML checkbox behavior: Checkboxes are only sent to the server if they are on; if they are off, no name/value pair is sent. You are going to have trouble turning off values with the above code.
So you need to run through your known list of values and check for them in the $_POST parameters.
You should use an array name and it will be an array in PHP.
As ndp said, if a checkbox is unchecked, its value will not be transmitted. So you need to use a hidden input field with the same name before the checkbox input field, with the "off" value.
<label for="one">One</label>
<input type="hidden" name="checkboxes[one]" value="off"/>
<input type="checkbox" name="checkboxes[one]" id="one" value="on"/>
Remember checked="checked" if it should be default to on.
You can now loop the checkboxes with POST or GET
foreach ($_POST['checkboxes'] as $key => $value) {
//something
}
if($_POST['submit']){
if(!empty($applicant_id)){
$sql = "UPDATE play SET ";
foreach($_POST as $key => $value){
if(($key != 'submit') && ($key != 'applicant_id')){
$sql .= $key . " = '" . ($value ? 'on' : 'off') . "',";
}
}
$sql = substr($sql, 0, -1);
$sql .= " WHERE ".$applicant_id." = $applicant_id";
$result = mysql_query($sql,$db) or die(mysql_error(). "<br />SQL: $sql");
}
}
The above assumes that all your inputs are checkboxes. If they aren't, you'll need to work out a convention to distinguish them.
Incidentally, your currently running UPDATE code is vulnerable to SQL injection because you aren't sanitizing your inputs with mysql_real_escape_string(). Cheers.
delete everything above :-)
name all you checkboxes like
and in foreach work with $_POST['out']
BUT! don't forget the golden rule: DOn't belive to the user. re-check every key=>value before writing to the datebase.