Jump to content

Recommended Posts

Hi,

I am kind of new to PHP, I looked around google and found what I was looking for (questionnaire to text) works perfectly fine with input type text and radio but when I try to do a checkbox it would not write the multiple answers on text file it would rather do one or return with an error. could someone please look at the script below and see what I am doing wrong?

 

 

<?php
if(isset($_POST['submit'])){
$firstName = "First Name:".$_POST['firstName']."
";
$lastName = "Last Name:".$_POST['lastName']."
";
$sex = "Sex:".$_POST['sex']."
";
$fruit = "Fav Fruits:".$_POST['fruit, fruit2, fruit3']."
";
$file=fopen("file.txt", "a");
fwrite($file, $firstName);
fwrite($file, $lastName);
fwrite($file, $sex);
fwrite($file, $fruit, $fruit2, $fruit3);
fclose($file);
}
?>


<form method="post">
      Name<input type="text" name="firstName" placeholder="First Name" required autocomplete="off"> <br>
      Last Name<input type="text" name="lastName" placeholder="Last Name" required autocomplete="off"> <br>
      Sex<input type="radio" name="sex" value="male">Male 
      <input type="radio" name="sex" value="female">Female<br>
      Fav Fruit<input type="checkbox" name="fruit" value="apple">Apple
      <input type="checkbox" name="fruit2" value="orange">Orange
      <input type="checkbox" name="fruit3" value="berry">Berry<br>
      <input type="submit" name="submit" value="Submit">
    </form>

 

Link to comment
https://forums.phpfreaks.com/topic/314942-php-checkbox-multiple-input-type/
Share on other sites

9 minutes ago, AlexMalex said:
$fruit = "Fav Fruits:".$_POST['fruit, fruit2, fruit3']."

What is this line supposed to be doing?  It is completely wrong.  What are you trying to do here?  If you want to do what you did with all of your other input data then you need to handle each fruit as a separate field, which they are.  But you need to check if each checkbox is set since they don't exist if they are not checked, unlike text inputs which always exist.

Okay I did the following by separating it to all individual lines. It does work, but on the output text file it shows the following.

First Name:a
Last Name:b
Sex:male
Fav Fruits:
Fav Fruits:orange
Fav Fruits:berry

 

I would like to have it like

 

Fav Fruits: orange berry (whichever selected)

rather than having them on individual lines. is that possible?

 

Also, on the text file exported. it stacks up all the answers in file repeatedly - I would like to have individual files for every submission. like file1.txt file2.txt ..... numbers going up.

 

many thanks in advance. 

 

<?php
if(isset($_POST['submit'])){
$firstName = "First Name:".$_POST['firstName']."
";
$lastName = "Last Name:".$_POST['lastName']."
";
$sex = "Sex:".$_POST['sex']."
";
$fruit = "Fav Fruits:".$_POST['fruit']."
";
$fruit2 = "Fav Fruits:".$_POST['fruit2']."
";
$fruit3 = "Fav Fruits:".$_POST['fruit3']."
";
$file=fopen("file.txt", "a");
fwrite($file, $firstName);
fwrite($file, $lastName);
fwrite($file, $sex);
fwrite($file, $fruit);
fwrite($file, $fruit2);
fwrite($file, $fruit3);
fclose($file);
}
?>


<form method="post">
      Name<input type="text" name="firstName" placeholder="First Name" required autocomplete="off"> <br>
      Last Name<input type="text" name="lastName" placeholder="Last Name" required autocomplete="off"> <br>
      Sex<input type="radio" name="sex" value="male">Male 
      <input type="radio" name="sex" value="female">Female<br>
      Fav Fruit<input type="checkbox" name="fruit" value="apple">Apple
      <input type="checkbox" name="fruit2" value="orange">Orange
      <input type="checkbox" name="fruit3" value="berry">Berry<br>
      <input type="submit" name="submit" value="Submit">
    </form>

 

 

A better way to handle multiple checkboxes like those is

Fav Fruit<input type="checkbox" name="fruit[]" value="apple">Apple
         <input type="checkbox" name="fruit[]" value="orange">Orange
         <input type="checkbox" name="fruit[]" value="berry">Berry<br>

so the checked ones are posted as an array

$_POST = Array
(
    [firstName] => Scott
    [lastName] => Chegg
    [sex] => male
    [fruit] => Array
        (
            [0] => apple
            [1] => berry
        )

)

When writing to the file

fwrite($file, join(', ', $_POST['fruit']);

 

Barand: what youve done seems very cool and pretty much makes my life easier in writing it as the questionare is very long. but it tells me that line 15 is wrong (your fwrite script). if you could look at line 9 also to see if that one is correct or does it need [] ?

Many thanks.

<?php
if(isset($_POST['submit'])){
$firstName = "First Name:".$_POST['firstName']."
";
$lastName = "Last Name:".$_POST['lastName']."
";
$sex = "Sex:".$_POST['sex']."
";
$fruit = "Fav Fruits:".$_POST['fruit']."
";
$file=fopen("file2.txt", "a");
fwrite($file, $firstName);
fwrite($file, $lastName);
fwrite($file, $sex);
fwrite($file, join(', ', $_POST['fruit']);
fclose($file);
}
?>


<form method="post">
      Name<input type="text" name="firstName" placeholder="First Name" required autocomplete="off"> <br>
      Last Name<input type="text" name="lastName" placeholder="Last Name" required autocomplete="off"> <br>
      Sex<input type="radio" name="sex" value="male">Male 
      <input type="radio" name="sex" value="female">Female<br>
      Fav Fruit<input type="checkbox" name="fruit[]" value="apple">Apple
      <input type="checkbox" name="fruit[]" value="orange">Orange
      <input type="checkbox" name="fruit[]" value="berry">Berry<br>
      <input type="submit" name="submit" value="Submit">
    </form>

 

8 minutes ago, AlexMalex said:

as the questionare is very long.

you should use a data driven design, where you have an array that defines the label, field type, placeholder text, choices (for checkbox/radio fields), and any other unique data per field. you would then loop over this defining data structure to dynamically produce the form, also use this when validating the submitted data, and use it when storing the data to a file/database, so that you can have some general-purpose code do the work, rather than writing out bespoke code for every field.

$_POST['fruit'] is an array, so line 9 would need to be

$fruit = "Fav Fruits:" . join(', ', $_POST['fruit']);

then

fwrite($file, $fruit);

I don't know what you subsequently intend to do with the text file but the format you use makes it both difficult to read and to process.

An improvent would be some form of delimiter character between fields and newlines at end of each record. eg

First Name:Laura|Last Name:Norder|Sex:female|Fav fruit:Apple, Orange
First Name:Scott|Last Name:Chegg|Sex:male|Fav fruit:Apple, Berry

 

[EDIT]

Ignore the above comment re format.

I just noticed you are (subtly) outputting newlines - I was looking for more explicit "\n";

28 minutes ago, Barand said:

$_POST['fruit'] is an array, so line 9 would need to be

$fruit = "Fav Fruits:" . join(', ', $_POST['fruit']);

then

fwrite($file, $fruit);

I don't know what you subsequently intend to do with the text file but the format you use makes it both difficult to read and to process.

An improvent would be some form of delimiter character between fields and newlines at end of each record. eg

First Name:Laura|Last Name:Norder|Sex:female|Fav fruit:Apple, Orange
First Name:Scott|Last Name:Chegg|Sex:male|Fav fruit:Apple, Berry

 

Thank you so much, you made my life so easy.....exactly what I wanted. 

 

I wanted to do the breaks - thats why I asked earlier if I can have it "rather" in a way that it saves every submission on a different file file1.txt file2.txt file3.txt and so on.... or alternatively I think its easier to have a breaker like ( ------------------  or even some <br><br><br>'s ) after every submission to distinguish between every time someone submits. 

 

could you guide me through this? on how or where to add what?

 

For the project i am doing txt format is perfectly fine as it is only a few submissions but I am sure the correct way of doing it would be some sort of database as you all mentioned.

 

 

Have you considered a common format such as ".csv" file EG

First_Name,Last_Name,Sex,Fruits
Scott,Chegg,male,"orange, berry"
Laura,Norder,female,"apple, orange"

code

if($_SERVER['REQUEST_METHOD']=='POST'){
    if (!file_exists('file.txt')) {
        file_put_contents('file.txt', "First_Name,Last_Name,Sex, Fruits\n");  // write header line
    }
    $file=fopen("file.txt", "a");
    $record = [$_POST['firstName'], $_POST['lastName'], $_POST['sex'], join(',', $_POST['fruit'])];
    fputcsv($file, $record);
}

 

  • Like 1

data driven example -

<?php

// file to save output in
// note: when storing data in a file, you must use file locking to make this concurrent safe (a database automatically does this for you)
$file_name = "file.txt";

// define fields - the array index is the field name, since these must be unique
$fields = [];
$fields['firstName'] = ['label'=>'First Name', 'type'=>'text', 'placeholder'=>'First Name', 'required'=>true, 'choices'=>[],];
$fields['lastName'] = ['label'=>'Last Name', 'type'=>'text', 'placeholder'=>'Last Name', 'required'=>true, 'choices'=>[],];
$fields['sex'] = ['label'=>'Sex', 'type'=>'radio', 'placeholder'=>'', 'required'=>false, 'choices'=>['male'=>'Male','female'=>'Female'],];
$fields['fruit'] = ['label'=>'Fav Fruit', 'type'=>'checkbox', 'placeholder'=>'', 'required'=>false, 'choices'=>['apple'=>'Apple','orange'=>'Orange','berry'=>'Berry'],];

// examine form data
// echo '<pre>'; print_r($_POST); echo '</pre>';

// post method form processing
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	// array to hold output lines
	$output = [];
	foreach($fields as $field=>$arr)
	{
		switch($arr['type'])
		{
		case "text":
			// add validation logic as needed
			
			$output[] = "{$arr['label']}: $_POST[$field]\n";
			break;
		case "radio":
			// add validation logic as needed
			
			$val = $_POST[$field] ?? 'not selected';
			$output[] = "{$arr['label']}: $val\n";
			break;
		case "checkbox":
			// add validation logic as needed
			
			$val = $_POST[$field] ?? 'not selected';
			$val = is_array($val) ? implode(', ',$val) : $val;
			$output[] = "{$arr['label']}: $val\n";
			break;
		}
	}
	// add separator
	$output[] = "------------------\n";
	file_put_contents($file_name,$output,FILE_APPEND);
}

?>
<form method="post">
<?php
foreach($fields as $field=>$arr)
{
	switch($arr['type'])
	{
	case "text":
		$req = ($arr['required'] ?? false) ? ' required' : '';
		echo "{$arr['label']}: <input type='{$arr['type']}' name='$field' placeholder='{$arr['placeholder']}'$req autocomplete='off'><br>\n";
        break;
	case "radio":
		echo "{$arr['label']}:";
		foreach($arr['choices'] as $value=>$label)
		{
			echo "<input type='radio' name='$field' value='$value'>$label ";
		}
		echo "<br>\n";
        break;
    case "checkbox":
		echo "{$arr['label']}:";
		foreach($arr['choices'] as $value=>$label)
		{
			echo "<input type='checkbox' name='{$field}[]' value='$value'>$label ";
		}
		echo "<br>\n";
        break;
	}
}
?>
	<input type="submit" name="submit" value="Submit">
</form>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.