如何使用php在CSV文件的一行中替换1个值? [英] How do I replace 1 value within a row in a CSV file using php?
问题描述
因此,这是我非常简单且基本的帐户系统(只是一个学校项目),我希望用户能够更改其密码.但是我不确定如何仅在一行中替换所有其他值都相同的情况下替换密码值.
So this is my very simple and basic account system (Just a school project), I would like the users to be able to change their password. But I am unsure on how to just replace the Password value within a row keeping all the other values the same.
CSV文件:
ID,Username,Email,DateJoined,Password,UserScore,profilePics
1,Test,Test@Test.com,03/12/2014,Test,10,uploads/profilePics/Test.jpg
2,Alfie,Alfie@test.com,05/12/2014,1234,136,uploads/profilePics/Alfie.png
PHP:("cNewPassword" =确认新密码)
PHP: ("cNewPassword" = confirm new password)
<?php
session_start();
if(empty($_POST['oldPassword']) || empty($_POST['newPassword']) || empty($_POST['cNewPassword'])) {
die("ERROR|Please fill out all of the fields.");
} else {
if($_POST['newPassword'] == $_POST['cNewPassword']) {
if ($_POST['oldPassword'] == $_SESSION['password']) {
$file = "Database/Users.csv";
$fh = fopen($file, "w");
while(! feof($file)) {
$rows = fgetcsv($file);
if ($rows[4] == $_POST['oldPassword'] && $rows[1] == $_SESSION['username']) {
//Replace line here
echo("SUCCESS|Password changed!");
}
}
fclose($file);
}
die("ERROR|Your current password is not correct!");
}
die("ERROR|New passwords do not match!");
}
?>
推荐答案
您将必须以读取模式打开文件,以写入模式打开一个临时文件,向其中写入修改后的数据,然后删除/重命名文件.我建议尝试建立一个真正的数据库并使用它,但是如果您要使用csv,则代码应该或多或少像这样:
You'll have to open file in read mode, open a temporary one in write mode, write there modified data, and then delete/rename files. I'd suggest trying to set up a real DB and work using it but if you're going for the csv, the code should look like more or less like this:
$input = fopen('Database/Users.csv', 'r'); //open for reading
$output = fopen('Database/temporary.csv', 'w'); //open for writing
while( false !== ( $data = fgetcsv($input) ) ){ //read each line as an array
//modify data here
if ($data[4] == $_POST['oldPassword'] && $data[1] == $_SESSION['username']) {
//Replace line here
$data[4] = $_POST['newPassword'];
echo("SUCCESS|Password changed!");
}
//write modified data to new file
fputcsv( $output, $data);
}
//close both files
fclose( $input );
fclose( $output );
//clean up
unlink('Database/Users.csv');// Delete obsolete BD
rename('Database/temporary.csv', 'Database/Users.csv'); //Rename temporary to new
希望有帮助.
这篇关于如何使用php在CSV文件的一行中替换1个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!