I realize this is a question that has been asked before ("Cannot use [] for reading"), but I'm having trouble wrapping my head around the answer and how to fix my particular function.
function check_required_checkbox($checkbox_name, $error, $is_multiple_checkboxes)
{
global $error_msgs;
if ($is_multiple_checkboxes == true)
{
if (!isset($_POST[$checkbox_name][]))
{
$error_msgs[] = $error;
}
else if ($is_multiple_checkboxes == false)
{
if (!isset($_POST[$checkbox_name]))
{
$error_msgs[] = $error;
}
}
}
The problem line is 6, !isset($_POST[$checkbox_name][]), and I'm not understanding how the correct way I should write it. I saw instances of using brackets but !isset($_POST[{$checkbox_name}][]) isn't correct either.
When I have multiple checkboxes that use name="radda[]", I want my function to check that all of the checkboxes with a specific name are checked, and if not, add $error to the $error_msgs[] array.
EDIT:
I discussed with the department that was requesting a rewrite of the old form. Instead of using checkboxes, I switched it to a list of all of the borrower's rights and responsibilities, and then used a radio button below the list to ask the user to select "yes" or "no" on whether they read the list. Then I made it required to select "yes" or "no" and added validation that if "no" was selected, they wouldn't be able to submit the application. This was far easier than trying to make a bunch of checkboxes required. I do appreciate the help that everyone offered though.
If I understood what you need.
Try to define the $checkbox_name variable and then access the POST.
$checkbox_name = 'radda';
if (isset($_POST[$checkbox_name]) && !is_array($_POST[$checkbox_name]))
{
$error_msgs[] = $error;
}
Something like that should work.
Here is a similar thread: Retrieve an associative array value with a variable as key
Related
I have a html form which displays the contents of a mySQL table called banner, containg multiple banner elements, that appear like:
Im using PHP Codeigniter. I want users to be able to update the display checkbox and submit, storing the values 1 and 0 in the database for checked / not.
FormView
<td>
<input type="checkbox" name="bdisplay[]" value="<?php $bannerId?>" <?php if ($displaycheck==1): ?> checked <?php endif;?>>
<?php echo $banner->bdisplay; ?>
</td>
The function for form submission. It creates a new associative array, if checkbox ticked id=>1 or else id=>0.
public function do_updatedisp()
{
$results = array();
foreach($_POST['bdisplay'] as $onedisplay)
{
if(!empty($onedisplay))
{
array_push($results, $results[$onedisplay]=1);
}
else
{
array_push($results, $results[$onedisplay]=0);
}
$this->bannerM->form_update($results);
}
}
The banner model:
function form_update($results)
{
foreach($results as $result=>$value)
{
$this->db->set('bdisplay', $value);
$this->db->where('banner_id', $result);
$this->db->insert('banner');
}
}
This is the error I get:
Cannot add or update a child row: a foreign key constraint fails (vigilantx.banner, CONSTRAINT FK__usarios FOREIGN KEY (user_id) REFERENCES usarios (user_id))
I know there is nothing wrong with the foreign key, there is error elsewhere but
I have been stuck on this for far too long! Any help appreciated!
i'm not sure but i think the problem is the insert method because everytime a user clicks on this checkbox he inserts a new row to your table which could be problematic (don't know your db schema but i think thats causing the foreign key troubles)
try this instead
function form_update($results)
{
foreach($results as $result=>$value)
{
$this->db->set('bdisplay', $value);
$this->db->where('banner_id', $result);
$this->db->update('banner');
}
}
I guess you are making things a big complicated for yourself, you are doing things correctly but doing too much. Basically the value you have implemented the form is correct, for instance you form with checkbox
display banner
when a form is submitted irrespective of any HTTP method being used, on server side only set values are passed therefore on php side if the checkbox is not checked then it will not be present to PHP runtime therefore if you simply check.
<?php
// using HTTP get method
// default value for banner display is zero
$banner_display = 0;
if(isset($_GET['bdisplay'])
$banner_display = 1;
// further write code to do whatever processing you would like to do
?>
The above code works in case you simply have a single checkbox which is optional to user furthermore using just if statement is a optimal way of writing code which help in generating extra branching instructions
I have a basic math question that the user has to answer before they can send an email:
$first_num = rand(1, 4);
$second_num = rand(1, 4);
$send = #$_POST['send'];
if($send){
//The user's answer from the input box
$answer = #$_POST["answer"];
if($answer == $first_num + $second_num) {
//Do stuff
}
else {
$error_message = "You answered the question wrong!";
}
}
I answer the question correctly (unless my first grade math is off!) yet it says I have the question wrong. I am not sure what the issue is but I imagine it is something to do with the fact that php executes immediately when the page is loaded and so new numbers are generated as soon as the user presses the submit button? Or am I way off? If that is the case, what can be done to solve this?
The problem is that you are setting your values every time your script is called. So when you post your form, two new values are set and they are likely not the same values as when you called the script the first time to show the form.
You should store your variables in a session and retrieve these values when you process your post request.
Something like:
session_start();
if (!isset($_SESSION['numbers']))
{
$_SESSION['numbers']['first'] = rand(1, 4);
$_SESSION['numbers']['second'] = rand(1, 4);
}
...
if ($answer == $_SESSION['numbers']['first'] + $_SESSION['numbers']['second']) {
//Do stuff
/**
unset the variables after successfully processing the form so that
you will get new ones next time you open the form
*/
unset($_SESSION['numbers']);
...
Note that you will need to use the session variables everywhere where you are using your own variables right now.
You should include the two numbers as hidden form inputs in your HTML, and then do the math with the entries in your $_POST array.
Make your code start like this instead:
$first_num = $_POST["first_num"];
$second_num = $_POST["second_num"];
I have a page that has 39 check boxes. The check boxes in my example resemble form names. My problem is that with 39 check boxes I need a way to store what forms were given to a student. Currently what I have set up is that each form is separated with a comma and a quote so that when a report is run the Administrator can use a CSV download option and group which forms a student has received. This works but is very rudimentary and also gives a bad side affect that before each form name a / is present because mysql escapes quotes.
This is what I currently have :
if ($this->input->post('action') == 'additional') {
$givenforms = "";
foreach ($this->input->post('form') as $forms) {
$givenforms .= ', "' . $forms . '"';
}
$comments = 'This student was given' . $givenforms . '';
if (($this->input->post('action') == 'additional') && ($this->input->post('other') == 'OTHER')) {
$comments .= ', '.$this->input->post('counselorcomments');
}
}
Again in the database the results will look like : This student was given "xyz", "eoe", "wwo",
Pretty much I just need ideas on how to store which forms a student was given, and if needed if all 39 forms are given to a student I need to store all forms the student was given for later reporting. (even though 39 forms wont be given)
Sounds like you need a one:many relationship between students and forms. Might want to do a little research on that topic.
I consider it generally to be pretty poor form to store comma separated values in a single field in a database, if you're doing that, it's almost always a sign that you need (at least) another table.
An hour or two of refactoring what I had with the CSV paid off quite well. I am very very pleased with the reporting/analytical possibilities of the knew information and the way I got it stored now.
Couple snippets of code for any one else looking into doing something like this! :
if ($this->form_validation->run() == FALSE) { // This stuff is self explanatory RT(F)M if you will :)
$this->cont();
} else {
$this->load->model('queue_model'); // Load model
$session = $this->uri->segment(3); // Gets the session id
$counselor = $this->session->userdata('username'); // I get counsellor names from the username they log in by joining between the two tables
if ($this->input->post('action') == 'Additional') { // If additional forms is checked do the following
foreach ($this->input->post('form') as $form_id) { // for each form submitted take the session Id from above and insert it into the table forms with the foreach $form_id variable
$this->queue_model->forms($session, $form_id);
}
if (($this->input->post('action') == 'Additional') && ($this->input->post('addother') == 'addotherinfo')) { // If forms were submitted and a addotherinfo was [checked] add comments
$comments = ''.$this->input->post('action'). ' - '.$this->input->post('counselorcomments').'';
} else {
$comments = $this->input->post('action');
}
}
Also adding in a forms table (with the ID's and form names) allowed me to dynamically make the check boxes like so :
<?php
foreach ($elevennine as $form) { ?>
<label id="form"><input type="checkbox" name="form[]" value="<?php echo $form['form_id'] ?>" <?php echo set_checkbox('form', $form['form_id']) ?>><?php echo $form['forms'] ?></label>
<?php }
?>
Thanks for all the great ideas!
I have a problem:
Here's a block of the code:
function draw()
{
$out_string="";
$out_string.=$this->script;
reset($this->fields);
$num_list_box=0;
while( $field = each($this->fields) )
{
if (isset($this->fields[$field[1]->field]->options))
{
if (preg_match("/<script type=\"text\/javascript\">/i",$this->fields[$field[1]->field]->options[0][1])&& $this->fields[$field[1]->field]->value!="")
{
if ($num_list_box==0) $out_string.= "<script type=\"text/javascript\">levels.forValue(\"".$field_prev[0]."\").setDefaultOptions(\"".$this->fields[$field[1]->field]->value."\");</script>\n";
else $out_string.= "<script type=\"text/javascript\">levels.forValue(\"".$field_prev[0]."\").forValue(\"".$field_prev[1]."\").setDefaultOptions(\"".$this->fields[$field[1]->field]->value."\");</script>\n";
$field_prev[]=$this->fields[$field[1]->field]->value;
$num_list_box++;
} else
{
$field_prev[0]=$this->fields[$field[1]->field]->value;
$num_list_box=0;
}
}
}
$out_string.=$this->draw_title();
$out_string.=$this->draw_header();
$out_string.= "<table class=\"forms\">\n";
$field=array_keys($this->fields);
reset($field);
$ind_first=true;
while( list($pos,$field_name) = each($field) )
{
if ($this->num_cols>0) {
if ($this->fields[$field_name]->col==1){
if ($ind_first) $ind_first=false;else $out_string.="</tr>";
$out_string.="<tr><td class=\"field_title\">";}
else $out_string.="<td class=\"field_title\">";
$out_string.= $this->fields[$field_name]->title."</td>";
$colspan="";
if ($this->num_cols>1) {
if ($this->fields[$field_name]->col==1 && array_key_exists($pos+1,$field) && $this->fields[$field[$pos+1]]->col==1)
$colspan="colspan=\"3\"";
}
$out_string.="<td class=\"field_value\" $colspan>";
$out_string.=$this->fields[$field_name]->draw()."</td>";
} else
{
if ($ind_first) $ind_first=false;else $out_string.="</tr>";
$out_string.="<tr><td class=\"field_value\">".$this->fields[$field_name]->title."<br />";
$out_string.=$this->fields[$field_name]->draw()."</td>";
}
}
$out_string.= "</tr></table>\n";
return $out_string;
}
This above block of code produces something like this:
I want it such that in the example provided that the word "Transaction" is above the text box.
Please help, the person that programmed this part is indisposed and we've got a deadline.
Thanks for the help.
P.S. The CSS class name for the text is: field_title and the one for the textbox is field_value
Thanks once more.
You will have to debug that code to find out when the label "Transaction" is getting inserted into that cludge of table code. Once you find where "Transaction" is inserted you can then create new logic to add another TR that colspans the table and place the label on that new row.
Good luck, looks like a headache.
Your code is apparently building a rather complex form based on some data ($fields property of the class). I guess some "field settings" (like col) describe how the form should look like.
So, your code is doing things that are neither described in your question nor in the code itself. Furthermore, we have no clue what the complete form currently looks like, so we can't even guess the intention of the code.
Your request, to let the description appear above the selection box(?) could be done probably throwing away half of the code, but that won't help you.
PS: Please check the FAQ - this site is for questions, not for finding people to do your (or elses) work. You should really have a programmer solve your problem directly having access to the whole page.
I've got a form that calculates how many times a person has chosen a value. Each question has 3 answers with a value of either "self", "others", or "social". Whichever has the MOST gets returned as the result.
Ultimately, I need a custom post field hidden from the user, populated with this result. Currently it's being display after form submission with:
return $confirmation
I've got http://pastie.org/3312298 pasted in the bottom of my functions.php file.
I'm not quite sure how to get the result into the box before the form gets submitted to us as an entry.
www.webdesignsalemoregon.com/surveytest
is where it's lying right now
You're taking a way complicated route of doing this.
give each radio button for 'self' <input name='self'>, and do the same for the rest
$self_answers = count($_POST['self']);
$others_answers = count($_POST['others']);
$social_answers = count($_POST['social']);
$max = max($self_answers, $others_answers, $social_answers) ;
if($max == $self_answers) {
$greatest = "self";
} else if($max == $others_answers) {
$greatest = "others";
} else {
$greatest = "social";
}