-2
$testarray['player1'] = $player1Plays;
$testarray['player2'] = $player2Plays;
$testarray['result'] = $result;

print_r ($testarray);

$yoyo = serialize ($testarray);

$file = 'prevdata.dat';
fopen ($file, 'w');
file_put_contents($file, trim($yoyo) . PHP_EOL, FILE_APPEND);

I'm making a small rock, paper, scissors game for class and need to save each move and results to a file. This is what I have so far and it works to serialize the data and save it to the file, but every time I play the game again it writes over the data currently in the file (I thought 'FILE_APPEND' was supposed to add on). The full code is provided here https://eval.in/624620

Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
Baker2795
  • 237
  • 3
  • 12

2 Answers2

1

Change

$file = 'prevdata.dat';
fopen ($file, 'w');
file_put_contents($file, trim($yoyo) . PHP_EOL, FILE_APPEND);

to either

$fp = fopen('prevdata.dat', 'a'); fwrite($fp, trim($yoyo));

or

file_put_contents('prevdata.dat', trim($yoyo), FILE_APPEND);
StackSlave
  • 10,613
  • 2
  • 18
  • 35
  • I guess while I was messing around with 'file_put_contents' I added fopen to my file trying to get it to work before adding append to 'put_contents'. after removing the fopen line the code worked fine. – Baker2795 Aug 18 '16 at 05:03
  • @PHPglue is there a way to set a limit to how many previous games I want to save to the file? Say I only wanted to record 25 games, is there a way to overwrite the oldest data? – Baker2795 Aug 18 '16 at 05:24
0

It's important to use the right mode of the fopen function. You need to put the pointer (you can think of it as a writing head) at the end of the file like this:

fopen($file, 'a');

Take a look at the documentation to see all the possible modes.

http://php.net/manual/en/function.fopen.php

mgadrat
  • 154
  • 1
  • 5