Jump to content

Piece of Cake


bazazu

Recommended Posts

Hi Im sure am missing something very easy on this one can someone help me find it please..

 

INDEX.HTML

<html>
<head>
	<title>Example form</title>
</head>
<body>
<form name="analysis" id="analysis" action="index3.php" method="POST">
           <table width="70%">
			<h5><strong>A=agree B=somewhat agree C=neutral D=disagree</strong></h5>
				<tr>
					<th align="left">SECTION 1</th>
						<td align="right">A   B&nbsp  C   D </td>
				</tr>
			<tr class="question">
			<td class="section">Love makes the world go round.
					<td align="right">
						<input type="radio" name="love1" id="sec11" value="0">
						<input type="radio" name="love1" id="sec11" value="2">
						<input type="radio" name="love1" id="sec11" value="5">
						<input type="radio" name="love1" id="sec11" value="10">
			</tr>
			<tr class="question">
			<td class="section">What goes around comes around
					<td align="right">
						<input type="radio" name="love2" id="sec12" value="0">
						<input type="radio" name="love2" id="sec12" value="2">
						<input type="radio" name="love2" id="sec12" value="5">
						<input type="radio" name="love2" id="sec12" value="10">
			<tr class="question">
			<td class="section">Love thy neighbor but dont get caught
					<td align="right">
						<input type="radio" name="love3" id="sec13" value="0">
						<input type="radio" name="love3" id="sec13" value="2">
						<input type="radio" name="love3" id="sec13" value="5">
						<input type="radio" name="love3" id="sec13" value="10">
			<tr class="question">
			<td class="section">youre a volcano and he/shes a tornado
					<td align="right">
						<input type="radio" name="love4" id="sec14" value="0">
						<input type="radio" name="love4" id="sec14" value="2">
						<input type="radio" name="love4" id="sec14" value="5">
						<input type="radio" name="love4" id="sec14" value="10">
		</table>
	<p>
		<b>
			About you:
		</b>
	</p>
	<p>
		<textarea rows="5" name="addtext" cols="65"></textarea>
	</p>

	<div>
		<input type="submit" id="createcsv" name="createcsv">
	</div>
</form>
</body>
</html>

 

INDEX3.PHP

 

<?php

// Receiving variables
@$pfw_ip= $_SERVER['REMOTE_ADDR'];
@$love1 = addslashes($_POST['love1']);
@$love2 = addslashes($_POST['love2']);
@$love3 = addslashes($_POST['love3']);
@$love4 = addslashes($_POST['love4']);
@$addtext = addslashes($_POST['addtext']);

// Validation
//saving record in a text file
if ($_POST)
{
    foreach ($_POST as $key => $value)
    {
        $_POST[$key] = addslashes($value);
    }
     
$pfw_file_name = "info.csv";   
    // Let's store this as an array so we can loop through it
    $pfw_first_row = array("love1","love2","love3","love4","addtext");

   if(!file_exists($pfw_file_name))
    {
        $pfw_is_first_row = true;
        // If the file doesn't exist, let's create it
        if (!$fh = fopen($pfw_file_name, "w+"))
        {
            die("Cannot create file {$pfw_file_name}");
        }
        else
        {
            fclose($fh);
        }
    }
    else
    {
        if (!$pfw_handle = fopen($pfw_file_name, 'r'))
        {
            die("Cannot open file ($pfw_file_name)");
        }
        // If the file exists, we want to read in its contents
        else
        {
            // Until we reach the end of the file
            while (!feof($pfw_handle))
            {
                // We'll read in one line at a time and store it in an array
                $existing_file[] = fgets($pfw_handle, 1024);
            }
            if (count($existing_file) == 1)
            {
                $pfw_is_first_row = true;
            }
        }
        // We only opened it for reading
        fclose($pfw_handle);
    }
   
    // Now we're going to open the file for writing
    if (!$pfw_handle = fopen($pfw_file_name, 'w+'))
    {
        die("Cannot open file {$pfw_file_name} for writing");
    }
    else
    {
        // We need to write in the labels
        if ($pfw_is_first_row == true)
        {
            // Write the file one line at a time
            for ($i = 0; $i < count($pfw_first_row); $i++)
            {
                // We need to combine the first label and the first row of data
                $string = $pfw_first_row[$i] . "," . $_POST[$pfw_first_row[$i]] . "\r\n";
                fwrite($pfw_handle, $string);
            }
        }
        else
        {
            // Same as above, except $existing_file contains labels plus whatever
            // was already in the file
            for ($i = 0; $i < count($existing_file); $i++)
            {
                $string = rtrim($existing_file[$i], "\r\n") . "," . $_POST[$pfw_first_row[$i]] . "\r\n";
                fwrite($pfw_handle, $string);
            }
        }
        fclose($pfw_handle);
    }
     
}
echo("<p align='center'><font face='Arial' size='3' color='#FF0000'>thanx</font></p>");
?>

 

 

WHENEVER I WRITE SOMETHING IN THE about you BOX AND CLICK ENTER AND WRITE ONTO A NEW LINE.. THE DATA THAT GETS SAVED IN THE CSV GETS JUMBLED UP

 

have uploaded the files at http://www.bazazu.com/form/

for your reference..

the link to the csv file once generated would be http://www.bazazu.com/form/info.csv

 

please advice

Link to comment
Share on other sites

give an example what do you write in the form and what do you get output...

 

i filled the form 5 times

the first 3 times i did not write anything in the textbox

the 4 th time i wrote

one

two

three

four

and the 5th time i wrote

APPLE

BALL

CAT

DOG

 

The output that i got has been attached. you can also check it out at http://www.bazazu.com/form/info.csv

 

[attachment deleted by admin]

Link to comment
Share on other sites

Try to print the query and write here ...

i want that

A will be option 1

B option 2

C option 3

and D option 4:-)

 

yes, one radio input name per alternative.

setting 4 variables in that example.

 

at least that's the easy way! xD

Link to comment
Share on other sites

Yeah, csv files do not like random line breaks in the data (which are being added when you do a carriage return) because they use new lines to know when to move to the next record or line in the csv file.

 

You could probably just do str_replace("\r\n", " ", $fielddata); or str_replace("\n", " ", $fielddata); to get the output cleaned up.

 

If you want to keep the breks for some reason, I think you would need to convert them to br tags with nl2br().

Link to comment
Share on other sites

my actual form has 300 X 4 radio buttons and a textarea..

writing onto the text area is optional people can write anything onto it.

but when they press enter in the text area..and type LINE2 it gets saved onto the first column and you cant make out who entered what data.

the data should look like this attachment .. sorry for not explaining it well earliar

 

[attachment deleted by admin]

Link to comment
Share on other sites

presume for the moment, you have selected all A's for your radio buttons and entered

Apple

Cat

Dog

Done

in your text box.

 

What do you want your csv file to look like?

 

Assuming someone before you filled the form with all D's and nothing in text area, and you filled the form with all A's with

Apple

Cat

Dog

Done

in the text area... then it should look like this attachment

 

[attachment deleted by admin]

Link to comment
Share on other sites

Ok... GENERALLY speaking your csv file should look like this (using the pipe to delimit the fields)

 

10|10|10|10|

0|0|0|0|Apple, Cat, Dog, Done

 

where the elements are: love1|love2|love3|love4|addtext

each line ends with a new line

that way each line represents someones choices

 

You might add two more elements - username/id AND timestamp of when the record was added

 

With it set up that way it is easy to get back a user's answers to display to them later OR to use the info in other ways

 

Does that make sense to you? If so, we can work on how to achieve that.

 

Link to comment
Share on other sites

Ok... GENERALLY speaking your csv file should look like this (using the pipe to delimit the fields)

 

10|10|10|10|

0|0|0|0|Apple, Cat, Dog, Done

 

where the elements are: love1|love2|love3|love4|addtext

each line ends with a new line

that way each line represents someones choices

 

You might add two more elements - username/id AND timestamp of when the record was added

 

With it set up that way it is easy to get back a user's answers to display to them later OR to use the info in other ways

 

Does that make sense to you? If so, we can work on how to achieve that.

 

 

yup exactly :)

Link to comment
Share on other sites

Here, this rough example should help you get started properly (you will need to test and sanitize any form data)...

<?php
/* obtain the form data */
$love1 = $_POST['love1'];
$love2 = $_POST['love2'];
$love3 = $_POST['love3'];
$love4 = $_POST['love4'];
$addtext = $_POST['addtext'];

/* make sure love* variables only contain valid values */
/* cleanse textarea content */

/* get the current timestamp */
$ts = time();

/* set csv file name */
$pfw_file_name = "info.csv"; 

/* create the new row of data */
$new_data = $ts . "|" . $love1 . "|" . $love2 . "|" . $love3 . "|" . $love4 . "|" . $addtext  . "\n";

/* append the new row to the file */
$fh = fopen($$pfw_file_name, 'a') or die("can't open file"); 
fwrite($fh, $new_data); 
fclose($fh); 

echo("<p align='center'><font face='Arial' size='3' color='#FF0000'>thanx</font></p>");
?>

 

here is example how to read the file...

 

<?PHP
$pfw_file_name = "info.csv"; 
$lines = file($pfw_file_name);
$num_rows = count($lines);
$i = 0;
while($i<$num_rows) {
echo nl2br($lines[$i]);
$i ++;
}
?>

Link to comment
Share on other sites

Why are you getting in-depth about the other data when the problem obviously lies in putting new line characters in a csv field?

 

Because, sometimes, we feel the need to correct a far more serious problem - sloppy structure.

 

So he's going to repair it by using a comma delimited output from a field that the user may enter as

 

Apple

Orange

Pear

 

or

 

Apple Orange Pear

 

or

 

Apple, Orange, Pear

 

or

 

Any other combo you can think of

 

?

 

Enjoy writing code to handle every different scenario.

Link to comment
Share on other sites

And beyond that, I don't think lightbearers code even accounts for the new lines in the text field. When you are writing out the csv, and it encounters the first new line character in the textarea data, it is going to move the csv to the next line and will start putting data in the next row, the problem the OP posted about to begin with?

Link to comment
Share on other sites

And don't get smug with me...

 

..and don't get cocky with me. Nobody is under threat here. Well, you might be under threat of having a breakdown or having your ego put in check.

 

Sometimes it is better to steer the asker in a better direction regarding something they didn't ask about, like the structure. You know why? Because a lot of people are sick to death of sloppy code and sloppy developers who haven't been told any better.

 

 

Link to comment
Share on other sites

I understand if you think you had a better/different way to accomplish the task, I'm just saying that I thought the OP's problem was that he needed to stop the \r\n characters from breaking the CSV output.

 

Your example would work great, I would just say instead of nl2br() just string replace \r\n with a comma.

 

 

P.S. I meant the data items from the text area were comma delimited, not the file... I know what pipe delimited means.

 

Personally, I always try to rethink my form when one field is going to contain multiple pieces of data... it just makes it hard to work with.

 

;-)

 

Comments about whether or not I could read without considering the merit of what I was saying were uncalled for.

 

 

 

Link to comment
Share on other sites

And don't get smug with me...

 

..and don't get cocky with me. Nobody is under threat here. Well, you might be under threat of having a breakdown or having your ego put in check.

 

Sometimes it is better to steer the asker in a better direction regarding something they didn't ask about, like the structure. You know why? Because a lot of people are sick to death of sloppy code and sloppy developers who haven't been told any better.

 

Again, I guess I don't see the benefit in confusing the poster and still not correcting the original issue, but maybe that's just me ;)

Link to comment
Share on other sites

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.