Forum Moderators: coopster

Message Too Old, No Replies

Empty Field in CSV = Make entry for them

Make an entry in an empty field entered into a form writing to a CSV

         

trehahn

9:34 pm on Feb 3, 2006 (gmt 0)

10+ Year Member



I'm tryong to learn PHP, and have been able to get a form up writing to a CSV. I want to then be able to pull the CSV into Excel or even list the contents on a website. I have been able to do this, however when a field is left blank it does not write anything to that line in the CSV. So, because of this the line is shorter, and the field's do not line up, but are shifted the left.

I've considered checking for an input, but sometimes they'll have to be left blank, so these wouldn't work for my application. I've been searching for hours, upon hours and found no solution that has worked.

Basically what I want to do is insert maybe a space, or at least make sure the field is there. A space sounds like the best thing, then we've got no false data, if anyone has suggestions please let me know, and keep in mind I'm a newbie! LOL Here is my code:

<?php

if (isset($_POST['submit'])) {

$data = "";
if ($_POST['name']!= "") {
if ($data == "") {
$data = $_POST['name'];
} else {
$data = $data . "," . $_POST['name'];
}
}
if ($_POST['email']!= "") {
if ($data == "") {
$data = $_POST['email'];
} else {
$data = $data . "," . $_POST['email'];
}
}
if ($_POST['phone']!= "") {
if ($data == "") {
$data = $_POST['phone'];
} else {
$data = $data . "," . $_POST['phone'];
}
}
if ($_POST['call']!= "") {
if ($data == "") {
$data = $_POST['call'];
} else {
$data = $data . "," . $_POST['call'];
}
}
if ($_POST['comments']!= "") {
if ($data == "") {
$data = $_POST['comments'];
} else {
$data = $data . "," . $_POST['comments'];
}
}

$fp = fopen("data.csv","a");

if(!$fp) {
echo 'Error, the file could not be opened or there was an error creating it.';
exit;
}

fwrite($fp, $data."\n");

echo "Success, wrote to $data to data.csv!";
echo nl2br("\n");
echo nl2br("\n");

fclose($fp);
}
?>

I've tried changing each one a bit, but no matter what changes I make, I get errors. Being new, I'm unable to always fix the errors. Thanks for your help.

Tim

StupidScript

10:33 pm on Feb 3, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi trehahn, welcome to the forums!

You're off to a pretty good start.

In practice, your form should POST the same form elements in the same order every time, unless there are checkboxes that are optional. (In that case, they will still appear in the same order every time if they have been checked, or they'll be absent from their usual place in the order if they haven't been checked.)

In the following examples I'm going to assume that you have no checkboxes, so every form element will show in the same order, every time ... with nothing missing except for possibly some data. I'm using this order: name, email, phone, call, comments, submit.

First let's clean up what you've done ... here's a little rewrite of one of your conditional loops that can be applied to the others, as well:

if ([b]isset($_POST['name'][/b])) {

[b]$data = htmlentities($_POST['name']) . ",";[/b]

}

I've protected your Excel program by converting any special characters your user may have entered on the form to HTML entities. It's not as readable ... but it keeps some pretty nasty little hijacking attempts out. If your users are entering special characters like accented characters, this will also ensure that they don't mess with your functions.

Since we know 'name' is always the first element and we want it to be in every line of the CSV file, we don't need to check for the value of

$data
. All we need to do is include its value and follow that with a separator in preparation for the next element.

We want to include an entry for every element, even if there is no data in the user's POST ... otherwise, as you noticed, the columns fail to line up correctly. So ... if there is no data in the POSTed 'name' form element, we'll add an empty column instead. Here's the modified section:

if (isset($_POST['name'])) {

$data = htmlentities($_POST['name']) . ",";

}

else {

[b]$data = ",";[/b]

}

Continue with each form element's loop ... but make one very important change to subsequent loops: append the info to

$data
similar to what you did in your code, but a little faster ...

if (isset($_POST['email'])) {

[b]$data .= [/b]htmlentities($_POST['email']) . ",";

}

else {

[b]$data .= [/b]",";

}

Using the

[b].=[/b]
string operator simply appends the info to the string without having to recall the string's value each time.

Your last loop (comments) doesn't need the trailing comma, so we'll just add a newline character to break to the next row:

if (isset($_POST['comments'])) {

$data .= htmlentities($_POST['comments'])."\n";

}

else {

$data .= "\n";

}

So that takes care of the CSV columns.

Lastly, instead of adding to your script's overhead by performing a function to convert newlines into line breaks, just echo the line breaks:

echo "<br /><br />\n";

Keep on truckin'!

StupidScript

10:49 pm on Feb 3, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just for fun ... here's a look at another way to code that (no comments, so have a good time ingesting it!):

if (isset($_POST['submit'])) {

$data="";

foreach($_POST as $key => $value) {

if ($value) {

$data .= htmlentities($value) . ",";

}

else {

$data .= ",";

}

}

$data = substr($data,0,-1);

$data .= "\n";

[i]then your CSV dumping routine ...[/i]

}

Enjoy!

trehahn

11:02 pm on Feb 3, 2006 (gmt 0)

10+ Year Member



Wow! I came across this forum during a search, and thought I'd give posting a chance. I couldn't have been happier! Not only did what you mentioned work, but you've explained it VERY well! It isn't enough for me to just copy and paste and have it work, I want to be able to understand "how" it works as well. You've done a great job, thank you. Once I get this complete, I'll have to start a new project LOL I enjoy it!

Tim

StupidScript

11:32 pm on Feb 3, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You're welcome and I'm glad I could help.

I've got two more notes:

First, in the

$_POST
array, the form element names will always be there, but sometimes they won't have any value. This can really simplify the script for you. Using my second example for brevity, here's all you really have to do:

if (isset($_POST['submit'])) {

$data="";

foreach($_POST as $key => $value) {

$data .= htmlentities($value) . ",";

}

$data = substr($data,0,-1);

$data .= "\n";

[i]then your CSV dumping routine ...[/i]

}

If there's no

$value
, then only the comma delimiter will be written. (I didn't want to muck things up too much to shorten the learning curve ... but I think you're ready, now.)

Second, NEVER TRUST USER INPUT! (In case I didn't make myself clear ... NEVER TRUST USER INPUT!) That's the primary reason for using

htmlentities()
as I did. You ALWAYS want to perform some sort of security check or data munging on user input data before you do anything with it to protect your system.

See you around ...

trehahn

12:04 am on Feb 4, 2006 (gmt 0)

10+ Year Member



Yeah, ok....let me see if I understand you always trust user input, errrr wait LOL Just kidding.

I did run into a problem with it posting a blank line between each line, but I was able to find the problem, and with help from a friend realize why my edit had an error. It is working great now! Just FYI there is a great page out there that has a sortable listing script on it. I was going to hard code it, but this is just to cool to pass up! Here is the page:

[activewidgets.com...]

It reads the CSV file, and puts it into an Excel like look on the website, which is also sortable. I was impressed, though maybe others won't be. LOL Thanks again.

Tim