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
}
Related
Its' about a form to enter results of a soccer tournament.
The form got the already inputed data from the db and writes it into the value argument of the html form. If the value in the db NULL so in the html i got
value=""`
It's important that games with no inputs doesn't make a change in the db so i filter it before i do the query. But now could it happen that a game ends 0 : 0 But the db won't safe that. How can i say the system its not empty/NULL it is 0?
if(!empty($_POST[$tore_heim] OR !empty($_POST[$tore_gast]))){
$spiele_save = "UPDATE spiele SET tore_heim = '".$_POST[$tore_heim]."', tore_gast = '".$_POST[$tore_gast]."' WHERE id_spiele = ".$spiele_id[$i]."";
$spiele_save = mysqli_query($con, $spiele_save);};
};
Thank you deceze
if(isset($_POST[$tore_heim]) && strlen($_POST[$tore_heim]) > 0
OR
isset($_POST[$tore_gast]) && strlen($_POST[$tore_gast]) > 0)
The Problem is solved!
Check if value is '0': !empty($_POST[$tore_gast])) || $_POST[$tore_gast] === '0'
look at this example.
function isEmpty( $variable ){
return (
!isset($_POST[$variable]) ||
( empty($_POST[$variable]) && $_POST[$variable] !== "0" )
);
}
if ( !isEmpty($tore_heim) ){
// run your code here...
}
OK weird question.
Table consists of multiple fields. Some with data type int(5) and the rest with datatype int(11)
So lets take a row...
id =>int(5)
var1 =>int(11)
var2 =>int(11)
var3 =>int(11)
var4 =>int(11)
var5 =>int(5)
var6 =>int(11)
var7 =>int(11)
var8 =>int(11)
How can I count the fields in PHP BETWEEN id (int(5)) and var (int(5))
I need to return the values in the fields between using php... but Im stuck. Bad table design doesnt help...but Im stuck with it.
The full scenario is that i need to create an if statement which says, output the name and and data of the int(5) field IF any of the fields between it and the next int(5) contain data
sorry... ugly I know!!!
If run this so far
$sql2 = 'SHOW COLUMNS from services2';
$result2 = getDBResults($sql2, $level, $testing);
$total = count($result2);
$i=2;
while ($i<($total-1))
{
$data = $result2[$i]['Field'];
if ($result2[$i][1]=='int(5)')
{
$html .= '<h2>'.preg_replace('/(?<!\ )[A-Z]/', ' $0', $result2[$i]['Field']).'</h2>';
}
else
{
];
// "$result - This is a seperate query run previously to get the row
if ($result[0][$data] == 1)
{
$html .= '<p>'.preg_replace('/(?<!\ )[A-Z]/', ' $0', $data).'</p>';
}
}
$i++;
}
I have not had a chance to actually test this, so dont beat me up if you need to tweek it a bit to smooth off any rough edges.
But its a fairly standard, if not totally simple, process of processing over the column names result array in a loop and just remembering the last int(5) column name in a variable so you can use it, if and only if, you have found some data in any int(11) column types before seeing the next int(5) column type.
Now I understand why you had trouble explaining what you wanted, I am having the same trouble describing a solution.
Anyway, have a look at this code and see if it makes any sence to you.
$sql2 = 'SHOW COLUMNS from services2';
$columns = getDBResults($sql2, $level, $testing);
$total = count($columns);
$print_column = null;
$found_data = false;
foreach ( $columns as $idx => $column ) {
// skip first 2 columns
if ($idx < 3 ) { continue; }
// first time thru loop so remember the first int5 column name we saw
if ( $column['Type'] == 'int(5)' && empty($print_column) ) {
$print_column = $column['Field'];
$found_data = false;
continue;
}
// found the next int5 column, do we need to print anything
if ( $column['Type'] == 'int(5)' && $found_data ) {
// This is where you would do any output creation,
// I just kept it simple.
echo $result[0][$print_column];
// reset state and the next field that might be printed.
$found_data = false;
$print_column = $column['Field'];
continue;
}
// This may not need to be an if, but just in case you have other field types
// that you are not interested in processing I made it an if.
if ( $column['Type'] == 'int(11)' && ! empty($result[0][$column['Field']]) ) {
$found_data = true;
}
} // endforeach
Below is my code
if (!empty($_POST['ok'])) {
$errorMessage = array();
$loopcount = 0;
$i = 0;
foreach ($_POST['theDate'] AS $i => $theDate) {
if ($_POST['EW'][$i] == 'EW') {
$ew = "yes";
} else {
$ew = "no";
}
$i = $i + 1;
echo $ew;
}
}
its pulls the checkbox value of below and assigns it yes or now if value == ew
E/W<input name="EW[]" ID="EW[]" value="EW" type="checkbox" />
the issue is if check these
row checked
1 no
2 yes
3 no
3 yes
the out result when submitted is
row checked
1 yes
2 yes
3 no
4 no
It seems to stick anything checked as ew to the top and I don't get why here is a live working example that when submit is clicked echos with output.... all fields need to be filled but is u just add a number i will work
http://runningprofiles.com/tests/addbet.php
The checkbox is not submitted, if it does not have a value, thus, the 'yes' are the only ones in the loop. the index numbers for that field only from the submitted ones.
edit - clearification: if not checked - it its value does not get submitted.
foreach ($_POST['theDate'] AS $i => $theDate)
You missing the { at the end
like this
foreach ($_POST['theDate'] AS $i => $theDate){
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 */
}
}
}
Hi all
Now is 2 week that i searching for an answer to my problem and no luck. hope somone can help me on this
i have a chackbox option that i call from the database
<form style="margin-top:-30px" method="POST" action="extradata.php">
<?php
$sql = "SELECT ext_id,ext_price,ext_name,ext_description FROM tbl_extra ORDER by ext_id ASC";
$result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
$number = mysql_num_rows($result);
$i = 0;
while ($number > $i) {
$NA= mysql_result($result,$i,"ext_name");
$PR= mysql_result($result,$i,"ext_price");
print "<input type='checkbox' name='extra[]' value='$NA'></td>";
$i++;
}
?>
What i trying to do is to pass the value to extradata.php with 2 value
1.$NA,
2.$PR
when selected box then insert to the database the value of $NA to ex_tra and $PR to ex_price
the extradata.php
<?php
require_once 'library/config.php';
$id=$_POST['pd_id'];
$ssid=$_POST['ct_session_id'];
$total=$_POST['tot'];
$name=$_POST['basedes'];
$qty=$_POST['ct_qty'];
$extra_array = $_POST['extra'];
if ( $extra_array > "0" ) {
foreach ($extra_array as $one_extra) {
$source .= $one_extra.", "; }
$extra = substr($source, 0, -2);
} else {}
$result=mysql_query("INSERT INTO tbl_cart (pd_id, ct_qty, ct_session_id, ex_tra, ex_tra2, ex_price, ct_date) VALUES ('$id','$qty','$ssid','$extra','$name','$total', NOW())");
?>
Best regard to all
Sending two values in one variable is bound to get messy. I would just send the id and get the corresponding values from the database again in extradata.php.
If you really want to send multiple values, I would use fixed indices for the checkboxes (not extra[] but extra[SOME_NUMBER] and add a hidden field next to it (extra_pr[SOME_NUMBER]?) to pass the second value.
Note that you have to use fixed indices as unchecked checkboxes donĀ“t get posted but all hidden fields will get posted.