如何使用php替换CSV文件中的一行中的1个值?

时间:2015-01-04 16:01:53

标签: php csv

所以这是我非常简单和基本的帐户系统(只是一个学校项目),我希望用户能够更改他们的密码。但我不确定如何在一行中替换密码值,保持所有其他值相同。

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
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!");
}
?>

3 个答案:

答案 0 :(得分:8)

您必须以读取模式打开文件,在写入模式下打开文件,写入修改后的数据,然后删除/重命名文件。我建议尝试设置一个真正的数据库并使用它,但如果您要使用csv,代码看起来应该或多或少像这样:

$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

希望它有所帮助。

答案 1 :(得分:3)

我的建议是我的一个小功能,它会将您的数据库数据转换为可以修改然后返回原始状态的数组:

使用这组功能,您只需要精确分离每行/每行的数据。

function dbToArray($db, $row_separator = "\n", $data_separator = ",") {
    // Let's seperator each row of data.
    $separate = explode($row_separator, $db);

    // First line is always the table column name:

    $table_columns =
    $table_rows = array();

    foreach ($separate as $key => $row) {
        // Now let's get each column data out.
        $data = explode($data_separator, $row);

        // I always assume the first $row of data contains the column names.
        if ($key == 0)
            $table_columns = $data;
        else if ($key > 0 && count($table_columns) == count($data)) // Let's just make sure column amount matches.
            $table_rows[] = array_combine($table_columns, $data);
    }


    // Return an array with columns, and rows; each row data is bound with it's equivalent column name.
    return array(
        'columns' => $table_columns,
        'rows' => $table_rows,
    );
}

function arrayToDb(array $db, $row_separator = "\n", $data_separator = ",") {
    // A valid db array must contain a columns and rows keys.
    if (isset($db['columns']) && isset($db['rows'])) {
        // Let's now make sure it contains an array. (This might too exagerated of me to check that)
        $db['columns'] = (array) $db['columns'];
        $db['rows'] = (array) $db['rows'];

        // Now let's rewrite the db string imploding columns:
        $returnDB = implode($data_separator, $db['columns']).$row_separator;

        foreach ($db['rows'] as $row) {
            // And imploding each row data.
            $returnDB .= implode($data_separator, $row).$row_separator;
        }

        // Retunr the data.
        return $returnDB;
    }

    // Faaaaaaaaaaaail !
    return FALSE;
}

让我们指出我尝试使用你的db示例,即使多次测试它自己的结果,例如:dbToArray(arrayToDb(dbToArray())),它也能正常工作。

希望有所帮助。如果我能更清楚,不要犹豫。 :)

干杯,

答案 2 :(得分:0)

您需要一个3步骤来完成此操作(创建3个循环,可以优化为1或2个循环):

  1. 将相关数据加载到内存
  2. 更新所需数据
  3. 将数据保存到文件
  4. 祝你好运! :)

    PS。此外,您的密码绝不应以明文形式存储,内存(会话)或磁盘(csv),使用哈希函数!