постбэк не автозаполнение данными массива php

На этой странице есть раздел для редактирования нескольких строк «дочерних» данных на родительской странице.
Скриншот-editchild

кнопка «ОБНОВИТЬ» успешно отправляет данные через массив php в событие обратной передачи, которое мы успешно получаем и можем обновить базу данных.

Единственная проблема заключается в том, что форма возвращается к отображению исходных данных. Я подозреваю, что я делаю что-то не так с переменными, и они почему-то не совпадают, но я не совсем уверен. Кто-нибудь может определить мою ошибку?

<?php
require 'myheader.php'; // includes my db connection info
echo "<h2>Edit Children</h2>";
/*
this uses a multiline edit table to edit child info in place
and delete row buttons and and add button
*/
// initialize the child vars
$childid = '';
$subscribed = '';
$surname = '';
$firstname = '';
$commonname = '';
$othernames = '';
$dob = '';

// get the PARENT id from the session
$personid = $_SESSION['personid'];

if($personid === ""){
echo "Please select a member first<br>";
}else{
// Display the page
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "<hr><b>Member</b>";
$sqldemographics = "select personid, active, gender, dob, surname, firstname, commonname, othernames from members where personid = '" . $personid . "'";
//echo $sqldemographics . "<br>";
$demographics = $conn->query($sqldemographics);
if ($demographics->num_rows > 0)
{
echo "<table border='1'>";
echo "<tr><td><b>Surname</b></td><td><b>Common Name</b></td><td><b>First Name</b></td><td><b>Other Names</b></td><td><b>Date of Birth</b></td></tr>";
// output data of each row
while($row = $demographics->fetch_assoc()) {
echo "<td>" . $row['surname'] . "</td><td>" . $row['commonname'] . "</td><td>" . $row['firstname'] . "</td><td>" . $row['othernames'] . "</td>";
echo "<td>" . $row['dob'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "Unable to find matching member with personid: " . $personid . "<br>";
}
// done with MEMBER stuff

// -------  Move on to CHILD stuff  ------------------------
echo "<hr><b>Children</b>";
$sqlchildren = "select * from children inner join guardians on guardians.childid = children.childid where guardians.personid = '" . $personid . "'";
$children = $conn->query($sqlchildren);
if ($children->num_rows > 0)
{
// set up the form to display children AND allow edits
echo "<form method='post' action='" . htmlspecialchars($_SERVER['PHP_SELF']) . "'>";
echo "<table border='1'>";
echo "<tr><td><b>Subscribed</b></td><td><b>Surname</b></td><td><b>First Name</b></td><td><b>Common Name</b></td><td><b>Other Names</b></td><td><b>Date of Birth</b></td></tr>";
while($row = $children->fetch_array()) {
// use input arrays
echo "<tr>";
echo "<td>".$row['issubscribed']."</td>"; // subscriptions is not editable on this page
echo "<td><input type='text' name='surname[]' value='".$row['surname']."' maxlength='32' size='10' /></td>";
echo "<td><input type='text' name='firstname[]' value='".$row['firstname']."' maxlength='32' size='10' /></td>";
echo "<td><input type='text' name='commonname[]' value='".$row['commonname']."' maxlength='32' size='10' /></td>";
echo "<td><input type='text' name='othernames[]' value='".$row['othernames']."' maxlength='32' size='10' /></td>";
echo "<td><input type='text' name='dob[]' value='".$row['dob']."' maxlength='32' size='10' /></td>";
echo "<td><input type='hidden' name='childid[]' value='".$row['childid']."' /></td>";
echo "</tr>";
}
echo "<input type='submit' name='update' value='UPDATE' />";
echo "</table>";
echo "</form>";
} else {
echo "No associated child records found for " . $personname . "<br>";
}

echo "<a href='AddChild.php'>Add Children</a><br>";// ------ GET vs POST -----------------------------------------------
if($_SERVER["REQUEST_METHOD"] == "GET"){
// it's NOT a post back.

}else{
// it's a post back after editing child data into the form, so scrub and check the data
// make sure it's the "update" button
if(isset($_POST['update'])){
// its (zero indexed) arrays of each COLUMN
// since our algorithm is row based for the db insert it will have to explicitly index each array

// grab all the posted data into arrays
$childid = $_POST['childid'];
$subscribed = $_POST['subscribed'];
$surname = $_POST['surname'];
$firstname = $_POST['firstname'];
$commonname = $_POST['commonname'];
$othernames = $_POST['othernames'];
$dob = $_POST['dob'];

/*
print_r($childid);
echo "<br>";
print_r($firstname);
echo "<br>";
*/

// loop through the posted array of children
$index = 0;
foreach ($childid as $value => $ind_childid) {
$ind_subscribed = $subscribed[$index];
$ind_surname = $surname[$index];
$ind_firstname = $firstname[$index];
$ind_commonname = $commonname[$index];
$ind_othernames = $othernames[$index];
$ind_dob = $dob[$index];
++$index;
$sqlupdatechildren = "UPDATE children SET surname = '$ind_surname', firstname = '$ind_firstname', commonname = '$ind_commonname', othernames = '$ind_othernames', dob = '$ind_dob' WHERE childid = '$ind_childid'";
echo "$sqlupdatechildren<br>";
$conn->query($sqlupdatechildren); // insert the record
}

// !!! do we have to put the new data back into the form or something?

} // end "update" button
} // end postback section
$conn->close();  //close database
}

require 'myfooter.php';
?>

заранее спасибо
кругозор

0

Решение

Ваш код запрашивает базу данных и использует результаты для построения вывода HTML до обнаружение, было ли выполнено POST и обновление базы данных. Необходимо изменить порядок обработки, чтобы сначала выполнялась обработка POST, а затем генерировался вывод HTML.

2

Другие решения

для завершения, вот ИСПРАВЛЕННЫЙ код:

<?php
require 'playgroundsheader.php';
echo "<h2>Edit Children</h2>";
/*
this uses a multiline edit table to edit child info in place
and delete row buttons and and add button
*/
// initialize the child vars
$childid = '';
$subscribed = '';
$surname = '';
$firstname = '';
$commonname = '';
$othernames = '';
$dob = '';

// get the PARENT id from the session
$personid = $_SESSION['personid'];

if($personid === ""){
echo "Please select a member first<br>";
}else{
// Display the page
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "<hr><b>Member</b>";
$sqldemographics = "select personid, active, gender, dob, surname, firstname, commonname, othernames from members where personid = '" . $personid . "'";
//echo $sqldemographics . "<br>";
$demographics = $conn->query($sqldemographics);
if ($demographics->num_rows > 0)
{
echo "<table border='1'>";
echo "<tr><td><b>Surname</b></td><td><b>Common Name</b></td><td><b>First Name</b></td><td><b>Other Names</b></td><td><b>Date of Birth</b></td></tr>";
// output data of each row
while($row = $demographics->fetch_assoc()) {
echo "<td>" . $row['surname'] . "</td><td>" . $row['commonname'] . "</td><td>" . $row['firstname'] . "</td><td>" . $row['othernames'] . "</td>";
echo "<td>" . $row['dob'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "Unable to find matching member with personid: " . $personid . "<br>";
}
// done with MEMBER stuff

// -------  Move on to CHILD stuff  ------------------------

// ------ GET vs POST -----------------------------------------------
if($_SERVER["REQUEST_METHOD"] == "GET"){
// it's NOT a post back.

}else{
// it's a post back after editing child data into the form, so scrub and check the data
// make sure it's the "update" button
if(isset($_POST['update'])){
// its (zero indexed) arrays of each COLUMN
// since our algorithm is row based for the db insert it will have to explicitly index each array

// grab all the posted data into arrays
$childid = $_POST['childid'];
$subscribed = $_POST['subscribed'];
$surname = $_POST['surname'];
$firstname = $_POST['firstname'];
$commonname = $_POST['commonname'];
$othernames = $_POST['othernames'];
$dob = $_POST['dob'];

/*
print_r($childid);
echo "<br>";
print_r($firstname);
echo "<br>";
*/

// loop through the posted array of children
$index = 0;
foreach ($childid as $value => $ind_childid) {
$ind_subscribed = $subscribed[$index];
$ind_surname = $surname[$index];
$ind_firstname = $firstname[$index];
$ind_commonname = $commonname[$index];
$ind_othernames = $othernames[$index];
$ind_dob = $dob[$index];
++$index;
$sqlupdatechildren = "UPDATE children SET surname = '$ind_surname', firstname = '$ind_firstname', commonname = '$ind_commonname', othernames = '$ind_othernames', dob = '$ind_dob' WHERE childid = '$ind_childid'";
//echo "$sqlupdatechildren<br>";
$conn->query($sqlupdatechildren); // insert the record
}
} // end "update" button
} // end postback section

echo "<hr><b>Children</b>";
$sqlchildren = "select * from children inner join guardians on guardians.childid = children.childid where guardians.personid = '" . $personid . "'";
$children = $conn->query($sqlchildren);
if ($children->num_rows > 0)
{
// set up the form to display children AND allow edits
echo "<form method='post' action='" . htmlspecialchars($_SERVER['PHP_SELF']) . "'>";
echo "<table border='1'>";
echo "<tr><td><b>Subscribed</b></td><td><b>Surname</b></td><td><b>First Name</b></td><td><b>Common Name</b></td><td><b>Other Names</b></td><td><b>Date of Birth</b></td></tr>";
while($row = $children->fetch_array()) {
// use input arrays
echo "<tr>";
echo "<td>".$row['issubscribed']."</td>"; // subscriptions is not editable on this page
echo "<td><input type='text' name='surname[]' value='".$row['surname']."' maxlength='32' size='10' /></td>";
echo "<td><input type='text' name='firstname[]' value='".$row['firstname']."' maxlength='32' size='10' /></td>";
echo "<td><input type='text' name='commonname[]' value='".$row['commonname']."' maxlength='32' size='10' /></td>";
echo "<td><input type='text' name='othernames[]' value='".$row['othernames']."' maxlength='32' size='10' /></td>";
echo "<td><input type='text' name='dob[]' value='".$row['dob']."' maxlength='32' size='10' /></td>";
echo "<td><input type='hidden' name='childid[]' value='".$row['childid']."' /></td>";
echo "</tr>";
}
echo "<input type='submit' name='update' value='UPDATE' />";
echo "</table>";
echo "</form>";
} else {
echo "No associated child records found for " . $personname . "<br>";
}
// This part calls playgroundsAddChild.php
echo "<a href='playgroundsAddChild.php'>Add Children</a><br>";

$conn->close();  //close database
}
require 'playgroundsfooter.php';
?>
0

По вопросам рекламы [email protected]