Question

ive got the following fwrite code, with , separating the data and it ending in ))

$shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))';
fwrite($handle, $shapeType);

but this is how it saves in the text file...

,,,,))Triangle,180,120,80,Red))

why have the first set of

,,,,,))

appeared in front of what it should look like?

Was it helpful?

Solution

You need to add a new line character to the end of each line. Otherwise your lines will all run into each other.

Use PHP_EOL for this as it will automatically use the Operating System appropriate new line character sequence.

PHP_EOL (string)
The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2

$shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))'.PHP_EOL;

FYI, this might be a little cleaner to do using sprintf():

$shapeType = sprintf("%s,%s,%s,%s,%s))%s",
    $_POST['shapeType'],
    $_POST['triangleSide1'],
    $_POST['triangleSide2'],
    $_POST['triangleSide3'],
    $_POST['triangleColour'],
    PHP_EOL
);

OTHER TIPS

Without seeing more of the code I would guess that you post to the same file and you do not check if a POST request was made before you write your file. So probably you write to your file on a GET request as well, causing empty entries to appear.

You would need something like:

if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
  // ...
  $shapeType = $_POST['shapeType'].','.$_POST['triangleSide1'].','.$_POST['triangleSide2']
.','.$_POST['triangleSide3'].','.$_POST['triangleColour'].'))';
  fwrite($handle, $shapeType);
  // ...
}

Edit: By the way, you should probably use fputcsv as that takes care of escaping quotes, should you change something in the future that adds for example a description field.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top