PHP writing vars to txt file, results in duplicate commas/punctuation - php

I've got some data posted to a php file, and I need to save/append that data separated by commas to a text file. That's all fine and dandy and should be straightforwards, except for when I check the file I see that every comma has been written twice: once where it needs to be, and then again after the appended data but as a group of commas.
Here's what I've got:
<form action="signup-submit.php" method="post">
<fieldset>
<legend>New User Signup:</legend>
<label>Name:</label>
<input type="text" name="name" size="16" autofocus required/> <br/>
<label>Gender:</label>
<label><input type="radio" name="gender" value="m" /> Male</label>
<label><input type="radio" name="gender" value="f" checked /> Female</label> <br />
<label>Age: <input type="text" name="age" size="6" maxlength="2" required></label><br/>
<label>Personality Type: <input type="text" name="pType" maxlength="4" size="6" required/></label><br/>
<label>
Favorite OS:
<select name="os">
<option value="windows">Windows</option>
<option value="mac">Mac OS X</option>
<option value="linux">Linux</option>
</select>
</label><br/>
<label>
Seeking age:
<input name="min" type="text" size="6" maxlength="2" placeholder="min" required/>
to
<input name="max" type="text" size="6" maxlength="2" placeholder="max" required/>
</label><br/>
<input type="submit" value="Sign up"/>
</fieldset>
</form>
^that code posts the "user data" to signup-submit.php where it is stored into variables by the same var names.
$name = $_POST["name"];
$age = $_POST["age"];
$gender = $_POST["gender"];
$pType = $_POST["pType"];
$os = $_POST["os"];
$min = $_POST["min"];
$max = $_POST["max"];
$c = chr(44);
$s = "$name$c$age$c$gender$c$pType$c$os$c$min$c$max";
file_put_contents("single.txt", $s, FILE_APPEND);
?>
and the text file will unfailingly duplicate the commas as such:
Byron,21,m,INTP,windows,18,23,,,,,,
the variables are simply data posted to this file from a previous page. I've also tried every which way under the sun to save the data. In fact, if I write only text directly, I get no problems. When I used the csv function I got just commas and no data despite or so I believed formatting it correctly.

That's probably because sometime all your variables are empty, and you FILE_APPEND just commas.
To solve this do:
if (!empty($name) && !empty($age) && ...) {
$s = "$name,$age,$gender,$pType,$os,$min,$max";
file_put_contents("single.txt", $s, FILE_APPEND);
}
If these values are user input always double check them. PHP offers standard functions to sanitize: Sanitize Filters, also you will need input validation with custom rules (for example to check if a variable is within a certain range, but this is a different question).

Related

HTML Form - PHP Email with custom messages and tickbox

I have a HTML form with radio buttons, option boxes (drop down boxes), checkboxes, text fields and so on. I have the form pointed to another file called send.php to email the form on but how would I do this with the tickboxes and radio buttons and input text in between each answer? I would kind of like to format it like this:
Welcome: {name}
Your age group it between: {radio button with age groups}
And so on. I can't give you the actual code as it is private but I can give this instead which uses the kind of code and format:
<form action="send.php">
<input type="radio" name="AgeGroup" value="AgeGroup1"> 0-18<br>
<input type="radio" name="AgeGroup" value="AgeGroup2"> 19-29<br>
<input type="radio" name="period" value="AgeGroup3"> 30-39<br>
<input type="radio" name="period" value="AgeGroup4"> 40-49<br>
<input type="radio" name="period" value="AgeGroup5"> 50+<br>
<br><br><br><br>
<select name="Country">
<option value ="UK">United Kingdom</option>
<option value ="USA">United States</option>
</option></select>
<br><br><br><br>
<input type="text" name="PostCode" size="5">
<br><br><br><br>
<input type="text" name="HouseNumber" size="5">
<br><br><br><br>
<textarea id="Family" class="input" name="FamilyNumber" rows="10" cols="60"></textarea>
<br><br><br><br>
<input type="checkbox" name="Delievery" value="NextDay"> Next Day Delievery
<br>
<input type="checkbox" name="Delievery" value="TwoToFive"> 2-5 Day
<br>
<input type="checkbox" name="Outcome" value="Dismissed"> Dismissed
<br><br><br><br><br><br>
<center><button id="Send" type="submit" style="height:25px; width:100px; background-color: grey">Send</button></center>
</form>
Sorry it's so random. I ran out of ideas! Also sorry for my coding abilities, I don't normally do HTML!
Thanks.
I'm hoping this will help...if I'm understanding your question correctly.
Make sure to add a method to your form tag. For example:
<form action="send.php" method="post">. In send.php, you want to grab your variables by name attribute, for example:
$name = $_POST['Name'];
$ageGroup = $_POST['AgeGroup'];
And then you want to build out your email. PHP allows variables to be parsed in double quote strings, which can help you build your message the way you want it. (Reference)
$to = "person#example.com";
$subject = "Subject goes here";
$message = "Welcome: $name. Your age group is between: $ageGroup";
//note: headers are optional
$headers = "From: you#example.com" . "\r\n" . "CC: anotherperson#example.com";
mail($to, $subject, $message, $headers);
This is just a simple example, but this might be able to get you started.
you need to add method="POST" attribute to tag.
then, in send.php to read values, for example PostCode or HouseNumber:
echo "Post code: ".$_POST["PostCode"]."<br />";
echo "House number: "$_POST["HouseNumber"]";
for age:
if(isset($_POST["AgeGroup"]) {
echo "Age group: ".$_POST["AgeGroup"];
}
if(isset($_POST["period"]) {
echo "Age group: ".$_POST["period"];
}
for more info go to manual: http://php.net/manual/en/reserved.variables.post.php
This way you can group the radio buttons into one name, and you can get the values in the php as $_POST['name']
<form action="send.php" method="post">
<input type="radio" name="AgeGroup" value="0-18"> 0-18<br>
<input type="radio" name="AgeGroup" value="19-29"> 19-29<br>
<input type="radio" name="AgeGroup" value="30-39"> 30-39<br>
<input type="radio" name="AgeGroup" value="40-49"> 40-49<br>
<input type="radio" name="AgeGroup" value="50+"> 50+<br>
<select name="Country">
<option value ="UK">United Kingdom</option>
<option value ="USA">United States</option>
</option></select>
<input type="text" name="PostCode" size="5">
<input type="text" name="HouseNumber" size="5">
<textarea id="Family" class="input" name="FamilyNumber" rows="10" cols="60"></textarea>
<input type="checkbox" name="Delievery" value="NextDay"> Next Day Delievery
<br>
<input type="checkbox" name="Delievery" value="TwoToFive"> 2-5 Day
<br>
<input type="checkbox" name="Outcome" value="Dismissed"> Dismissed
<center><button id="Send" type="submit" style="height:25px; width:100px; background-color: grey">Send</button></center>
</form>

How to capture form text fields as an array like a radio group

I hope I ask this question correctly, and if not please direct me how to repair it. I have had it deleted as a post once already...
My goal is to submit a form with one drop down, with numbers like 100, 200, 300 (for how many T-shirts you want to order)... Then depending on what is selected from the drop down have a series of text boxes (for number placement) that must add up to the selected number of shirts you want to order from the dropdown.
My idea is to capture all these text fields in an array, and send them off to a function to be added...
Can someone assist me please?
Here is the form code I know does not work, but I want it to work...
<form>
<label>
<input type="checkbox" name="PoloDesign" value="100" id="PoloDesign_0" />
100</label>
<br />
<label>
<input type="checkbox" name="PoloDesign" value="200" id="PoloDesign_1" />
200</label>
<br />
<label>
<input type="checkbox" name="PoloDesign" value="300" id="PoloDesign_2" />
300</label>
<br />
<input type="text" name="name[1]" id="name1" value="{$name1}"/>
<input type="text" name="name[1]" id="name2" value="{$name2}"/>
<input type="text" name="name[1]" id="name3" value="{$name3}"/>
<input type="text" name="name[1]" id="name4" value="{$name4}"/>
<input type="text" name="name[1]" id="name5" value="{$name5}"/>
<input type="text" name="name[1]" id="name6" value="{$name6}"/>
<input type="text" name="name[1]" id="name7" value="{$name7}"/>
<input type="submit" value="submit"/>
</form>
Just change each
name="name[1]"
To
name="name[]"
Then the fields are posted as an array you can iterate through in PHP
if (is_array($_POST['name']):
foreach ($_POST['name'] as $key=>$field):
// do something here
$yourKey = $key +1;
$yourValue = $field;
I have changed your code a little and tried to make it work using regular expression:
<?php
$name_array = preg_grep('/name[1-9]*/', $_GET);
?>
So, basically it checks all submitted variables and creates array from all variables that have name at start and a number at end. So, the form part should change to look like this:
<input type="text" name="name1" id="name1" value="{$name1}"/>
<input type="text" name="name2" id="name2" value="{$name2}"/>
<input type="text" name="name3" id="name3" value="{$name3}"/>
<input type="text" name="name4" id="name4" value="{$name4}"/>
<input type="text" name="name5" id="name5" value="{$name5}"/>
<input type="text" name="name6" id="name6" value="{$name6}"/>
<input type="text" name="name7" id="name7" value="{$name7}"/>
I tested on Apache2 and PHP 5.3

How to accept a floating point value in an html form and send it to MySQL DB

I have created a form that contains fields used to accept a floating value as input. My goal is to be able to store these values in a DB and use them later on. Everything I've tried so far has resulted in failure.
I have tried changing the input field type from text to number, float, and even number with a small step size. It seems that when I request the value of the field with php and then send it to my DB, something goes wrong and stores only the nearest whole number. Ideas?
My form code is:
<form name ="chemAdd" action="submitChemData.php" method="POST" id="chemData">
<fieldset>
<legend>Chemical Information</legend>
<label for="chemName">Chemical Name:</label>
<input type="text" name="chemName" />
<label for="chemFormula">Molecular Formula:</label>
<input type="text" name="chemFormula" />
</fieldset>
<br />
<fieldset>
<legend>Antoine Constants</legend>
<label for="A">A:</label>
<input type="number" name="A" size="10" min="0" max="9999" step="0.00000001" />
<label for="B">B:</label>
<input type="float" name="B" size="10"/>
<label for="C">C:</label>
<input type="text" name="C" size="10"/>
<br /><br />
<label for="unitT">Unit (Temperature):</label>
<select name="unitT" >
<option value="K">Kelvin</option>
<option value="C">Celcius</option>
<option value="F">Fahrenheit</option>
</select>
<label for="unitP">Unit (Pressure):</label>
<select name="unitP" >
<option value="P">Pascal</option>
<option value="Hg">mm Hg</option>
<option value="bar">bar</option>
</select>
</fieldset>
<br />
<fieldset>
<legend>Reference Information</legend>
<label for="Tmin">Temp. Minimum:</label>
<input type="float" name="Tmin" size="10"/>
<label for="Tmax">Temp. Maximum:</label>
<input type="float" name="Tmax" size="10"/>
<br /><br />
<label for="Reference">Reference:</label>
<input type="text" name="Reference" size="60"/>
</fieldset>
<br />
<input type="submit" value="Add to Database" id="submit" />
</form>
</form>
My PHP code is:
require_once 'dbConnectChem.php';
$name = trim(strtoupper($_REQUEST['chemName']));
$formula= trim(strtoupper($_REQUEST['chemFormula']));
$A = $_REQUEST['A'];
$B = $_REQUEST['B'];
$C = $_REQUEST['C'];
$unitT = $_REQUEST['unitT'];
$unitP = $_REQUEST['unitP'];
$Tmin = $_REQUEST['Tmin'];
$Tmax = $_REQUEST['Tmax'];
$Reference = $_REQUEST['Reference'];
//INSERT Query
mysql_query("INSERT INTO Antoine (Name,Formula,A,B,C,unit_T,unit_P,Tmin,Tmax,Reference) VALUES ('{$name}','{$formula}','{$A}','{$B}','{$C}','{$unitT}','{$unitP}','{$Tmin}','{$Tmax}','{$Reference}') ")
or die(mysql_error());
Use DECIMAL data type instead of Float. AS described in this link, sometimes floating point values leads to issues, while Decimal works fine.
Use it like this way :
CREATE TABLE t1 (i INT, d1 DECIMAL(9,2), d2 DECIMAL(9,2));
Here 9 is the precision and 2 is the scale.Change it accordingly

Automatic check if input filled

There are 10 boxes in my website that I fill up based on my needs. From php code I prefer not to check them one by one like this. Instead of that I thought it would be a good idea to put check marks in each boxes and if I fill something in input field it should be checked so I can check however many checkboxes are filled and know how many boxes are filled.
if ($input1) {$total = "1";
if ($input2) {$total = "2";
}
}
Anybody knows how can I put automatically check into a checkbox when I start typing anything in it ? But it should be unchecked back if I delete what I wrote before sending it. Or if you guys have a better idea that would be nice also.
Thank you !
you could do this in JavaScript. Basically if the number of input text is the same of the checkboxes then you could use this function for example:
function change() {
var input_lengths = document.getElementsByName("textArray[]");
for(var i= 0; i < input_lengths.length;i++) {
if(document.getElementsByName("textArray[]").item(i).value != "") {
document.getElementsByName("checkArray[]").item(i).checked = true;
}
}
}
and your html could be:
<input type="text" name="textArray[]" value="" />
<input type="text" name="textArray[]" value="" />
<input type="text" name="textArray[]" value="" />
<input type="text" name="textArray[]" value="AAA" />
<input type="checkbox" name="checkArray[]" value="" />
<input type="checkbox" name="checkArray[]" value="" />
<input type="checkbox" name="checkArray[]" value="" />
<input type="checkbox" name="checkArray[]" value="" />
<input type="button" value="test" onclick="javascript:change()" />
why don't you name your checkboxes as an array e.g.:
<input type="checkbox" name="boxes[1]" />
<input type="checkbox" name="boxes[2]" />
then you can loop through the array in php and check each one individually
This is how i understood your problem:
you have 10 text inputs
you want to know how many of them contain actual input when they are submitted
your idea was to assign a checkbox input to each text input so that the corresponding checkboxes are checked when an input has text and is unchecked when an input has no text
Something very quick and dirty. You might want to name you inputs with a square bracket, so that php interprets that parameter as an array. Then you can iterate over an array and if the values are set you can count.
<html>
<body>
<?php
if(isset($_POST['input'])) {
$count = 0;
foreach($_POST['input'] as $value) {
if($value) {
$count++;
}
}
echo $count;
}
?>
<form action="testinputs.php" method="post">
<input name="input[]" value="" type="text">
<input name="input[]" value="" type="text">
<input name="input[]" value="" type="text">
<input name="input[]" value="" type="text">
<input name="input[]" value="" type="text">
<input name="input[]" value="" type="text">
<input type="submit"/>
</form>
</body>
</html>
If you want to do that on the client side, than I'd take something like jQuery and look how many inputs on my page contain any text inside them.

HTML checkbox field is being passed to PHP as checked even when it is not

First of all thanks in advance, this has been very frustrating and I'm hoping someone can see something I'm not, I am definitely no php expert. Well here' what is going on.
I have a form where I have a checkbox for people to opt in to our newletter. The form element looks like this:
<label for=newsletter accesskey=N class="checkbox">Signup for Cloverton's Newsletter</label>
<input name="newsletter" type="checkbox" id="newsletter" value="Yes" style="width:20px;" />
That is then submitted to a php file with this code:
if (isset($_POST['newsletter']) && $_POST['newsletter'] == 'Yes'){
echo "newletter yes";
$newsletter = 1;
}else{
echo "newsletter no";
$newsletter = 0;
}
$newsletter is then inserted into a database field.
The issue is that whether the box is checked or not it is being sent to php as true, so every entry is receiving the newsletter.
Any help would be greatly appreciated! Thanks!
Here's the full form minus the option list for the sake of brevity
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset>
<legend>Please fill in the following form all fields are required, thanks!</legend>
<label for=firstName accesskey=F><span class="required">*</span>First Name</label>
<input name="firstName" type="text" id="firstName" size="30" value="" />
<br />
<label for=lastName accesskey=L><span class="required">*</span>Last Name</label>
<input name="lastName" type="text" id="lastName" size="30" value="" />
<br />
<label for=email accesskey=E><span class="required">*</span>Email</label>
<input name="email" type="text" id="email" size="30" value="" />
<br />
<label for=city accesskey=C><span class="required">*</span>City</label>
<input name="city" type="text" id="city" size="30" value="" />
<br />
<label for=state accesskey=S><span class="required">*</span>State</label>
<select name="state" type="text" id="state">
<option value="AL">Alabama</option>
...
<option value="WY">Wyoming</option>
</select>
<br />
<label for=newsletter accesskey=N class="checkbox">Signup for Cloverton's Newsletter</label>
<input name="newsletter" type="checkbox" id="newsletter" value="Yes" style="width:20px;" />
<br />
<p><span class="required">*</span> Are you human?</p>
<label for=verify accesskey=V> 3 + 1 =</label>
<input name="verify" type="text" id="verify" size="4" value="" style="width: 30px;" /><br /><br />
<input type="submit" class="submit" id="submit" value="Submit" />
</fieldset>
</form>
Your code is correct. You most likely have a problem with your database insert/update logic. Why do you assume it is the PHP form handling?
This has just dawned on me.
If a checkbox is unchecked it isn't set in the $_POST superglobal. So if !isset($_POST['newsletter']) then it wasn't checked - if isset($_POST['newsletter']) it was checked.
Edit: Remove the 'yes' part - the value will never be yes, just true or 'on'.
Edit 2:
I've tested this to death. Change your code to:
if (isset($_POST['newsletter'])){
echo "newletter yes";
$newsletter = 1;
}else{
echo "newsletter no";
$newsletter = 0;
}
Remove the value="Yes" attribute from your checkbox input also. If you want it checking by default use checked="checked".

Categories