For a leaderboard for a game I am trying to use a csv file to store the cookie value for username and the corresponding user’s score. The code seems to be functional when its runs first but when another user completes the quiz the line of the csv file written with the previous user’s username and score is overwritten and replace with the current user’s username and score.
<?php session_start();
$scoreCookie = $_COOKIE['scoreCookieToPost'];
$leaderboard_data = array (
$_COOKIE['usernamecookie'],
$scoreCookie
);
$file = fopen("leaderboarddata.csv","w");
fputcsv($file, $leaderboard_data);
fclose($file);
?>
What changes would need to be made so each new submission would be put in a new row in the csv file and the first line would say Username,Score.
>Solution :
You would want to use the append mode of fopen ‘a’.
<?php session_start();
$scoreCookie = $_COOKIE['scoreCookieToPost'];
$leaderboard_data = array (
$_COOKIE['usernamecookie'],
$scoreCookie
);
$file = fopen("leaderboarddata.csv","a"); // a
fputcsv($file, $leaderboard_data );
fclose($file);
?>