PHP не изменяет первую строку после заголовка в файле CSV, но изменяет последующие строкиPhp

Кемеровские программисты php общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 PHP не изменяет первую строку после заголовка в файле CSV, но изменяет последующие строки

Сообщение Anonymous »

Я только изучаю все это и работаю над проектом. У меня есть HTML-форма, в которой успешно созданы пользователи, и вторая форма, которая правильно обновляет всех пользователей, кроме первого. Эти пользователи хранятся в CSV-файле с заголовками. Как я могу заставить его правильно изменять первого пользователя, как и остальных?

Код: Выделить всё


// READ CSV - READ DON'T WRITE

function readCSV($filename) { // This function reads the content of a CSV file and returns it as an array of rows.
$data = []; // Initialize an empty array to store CSV data.
$update = $data;

if (file_exists($filename)) {  // Check if the file exists before attempting to read.
$file = fopen($filename, 'r'); // Open the file for reading ('r' mode).

while (($row = fgetcsv($file)) !== false) { // Loop through each line of the CSV and add it to the $data array.
$data[] = $row; // Add each row to the $data array.
}
fclose($file); // Close the file after reading.
}
return $data; // Return the array containing the CSV data.
}

// WRITE CSV - ORIGINAL CONTENT

function writeCSV($filename, $headers, $data) {   // This function writes new content to a CSV file, overwriting any existing content.
$file = fopen($filename, 'w'); // Open the file for writing ('w' mode), which will overwrite existing content.
fputcsv($file, $headers); // Write the headers as the first row of the CSV file.
foreach ($data as $row) {  // Loop through each data row and write it to the CSV.
fputcsv($file, $row); // Write each row of data to the file.
}

fclose($file); // Close the file after writing all data.
}

// REWRITE CSV
function updateCSV($filename, $user_tag, $updated_data) {
$data = readCSV($filename);
foreach($data as $key => $row) {
if ($row[0] === $user_tag) {
$data[$key] = $updated_data; // Replace the whole row with updated data
break;
}
}

saveCSV($filename, $data); // Ensure this line is present to save changes
}

// SAVE CSV - WRITE CONTENT WITHOUT HEADERS
function saveCSV($filename, $data) {   // This function writes data to a CSV file, but it does not include a header row.
$file = fopen($filename, 'w'); // Open the file for writing ('w' mode), overwriting existing content.

foreach ($data as $row) {  // Loop through each data row and write it to the CSV.
fputcsv($file, $row); // Write each row of data to the file.
}
fclose($file); // Close the file after writing all data.
}

PHP, сопровождающий форму изменения:

Код: Выделить всё

// SESSION MANAGEMENT
session_start();

// CSV MANAGEMENT
include 'functions/csv_functions3.php'; // Include CSV functions for reading/writing CSV files
$users_csv = 'CSVs/users.csv'; // Define the path to the users CSV file

// Ensure the user is logged in before allowing an update
if (!isset($_SESSION['username'])) {
header('Location: login.php');
exit();
}

// POST DATA AND FORM MANAGEMENT
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Check if the form has been submitted
$bd = trim($_POST['bd']);
$bl = trim($_POST['bl']);
$mn = trim($_POST['mn']);
$fn = trim($_POST['fn']);
$sn = trim($_POST['sn']);
$tn2 = trim($_POST['tn2']);

// Handle file uploads
$tn = $_FILES['tn']['name'];
$sg = $_FILES['sg']['name'];

// Move uploaded files to your desired location (make sure the folder is writable)
move_uploaded_file($_FILES['tn']['tmp_name'], 'uploads/tbs/' . $tn);
move_uploaded_file($_FILES['sg']['tmp_name'], 'uploads/sgs/' . $sg);

$users = readCSV($users_csv); // Read existing users from the CSV

// Iterate over users to find the current one
foreach ($users as &$user) {
if ($user[1] === $_SESSION['username']) { // Match the username from session
// Update only the fields that need changing
$user[3] = $bd;
$user[4] = $bl;
$user[5] = $mn;
$user[6] = $fn;
$user[7] = $sn;
$user[8] = 'uploads/tbs/' . $tn;
$user[9] = 'uploads/sgs/' .  $sg;
$user[10] = $tn2;

// Retain the password
// $user[2] is the password, so we don't modify it here

// Rewrite the updated data to the CSV
updateCSV($users_csv, $user[0], $user); // Pass user_tag and the whole updated user array
break; // Stop once the user is found and updated
}
}

// Redirect after the update
header('Location:index.php'); // Redirect to the main index after successful update
exit(); // Terminate the script to ensure no further code is executed
}

Я пробовал всякое, в основном по указанию ИИ. Все работает правильно, за исключением того, что я не могу изменить первого пользователя, следующего за заголовком. При создании второго, третьего и т. д. пользователя его можно без проблем изменить с помощью формы.

Подробнее здесь: https://stackoverflow.com/questions/791 ... -subsequen
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Php»