Any way to break up data into array? - php

Problem
So a have some php code that gets student info from the db and outputs that info. The info is outputted in a input so the user can edit that info. Then when the user is done editing the info, I need to get the data, which I have. My problem is that I don't know how to break up that info so it's easy for me to alter the info in the db.
Student Table
studentID | firstname | lastname | teacherID
PHP Code that has the inputs
<form action="server/edit/students.php" method="post">
<table>
<tr>
<th>Student ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Teacher's Firstname</th>
<th>Teacher's Lastname</th>
</tr>
<?php
// get student info
$getStudent = $link->prepare("SELECT * FROM students");
$getStudent->execute();
$getStudent = $getStudent->fetchAll(PDO::FETCH_ASSOC);
$value = 0; // counts rows
// loop through each student
foreach ($getStudent as $student) {
$studentID = $student['studentID'];
$firstname = $student['firstname'];
$lastname = $student['lastname'];
$teacherID = $student['teacherID'];
// get teacher
$getTeacher = $link->prepare("SELECT * FROM teachers
WHERE teacherID = :teacherID");
$getTeacher->execute(array(
"teacherID" => $teacherID
));
$getTeacher = $getTeacher->fetchAll();
// loop through each teacher
foreach ($getTeacher as $teacher) {
$teacherFirstname = $teacher['firstname'];
$teacherLastname = $teacher['lastname'];
// output data
echo "
<tr>
<td><input type='text' name='studentID-$value' value='$studentID'></td>
<td><input type='text' name='firstname-$value' value='$firstname'></td>
<td><input type='text' name='lastname-$value' value='$lastname'></td>
<td><input type='text' name='teacherFirst-$value' value='$teacherFirstname'></td>
<td><input type='text' name='teacherLast-$value' value='$teacherLastname'></td>
</tr>
";
}
// add to row
$value += 1;
}
?>
</table>
<button type="submit" name="update">Update</button>
</form>
PHP Code that alters the db
$dataCount = 0;
foreach ($_POST as $data) {
if($dataCount % 5 === 0) {
echo "<br><br>";
echo $data . ", ";
} else {
echo $data . ", ";
}
$dataCount++;
}
What the form loops like on the screen
StudentID Firstname Lastname Teacher's Firstname Teacher's Lastname
_______________________________________________________________________________________
1 Bill Roy Jonathan Kung
2 Travis Roy Shanin Harnik

The easiest thing to do is use an array name in your input fields. This way your $_POST will be in a bunch of grouped arrays that are easily looped through:
<form action="server/edit/students.php" method="post">
<table>
<tr>
<th>Student ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Teacher's Firstname</th>
<th>Teacher's Lastname</th>
</tr>
<?php
// get student info
$getStudent = $link->prepare("SELECT * FROM students");
$getStudent->execute();
$getStudent = $getStudent->fetchAll(PDO::FETCH_ASSOC);
$value = 0; // counts rows
// loop through each student
foreach ($getStudent as $student) {
$studentID = $student['studentID'];
$firstname = $student['firstname'];
$lastname = $student['lastname'];
$teacherID = $student['teacherID'];
// get teacher
$getTeacher = $link->prepare("SELECT * FROM teachers WHERE teacherID = :teacherID");
$getTeacher->execute(array(
"teacherID" => $teacherID
));
$getTeacher = $getTeacher->fetchAll();
// loop through each teacher
foreach ($getTeacher as $teacher) {
$teacherFirstname = $teacher['firstname'];
$teacherLastname = $teacher['lastname'];
// output data
?>
<tr>
<td><input type='text' name='student[<?php echo $studentID ?>][firstname]' value='<?php echo $firstname ?>' /></td>
<td><input type='text' name='student[<?php echo $studentID ?>][lastname]' value='<?php echo $lastname ?>' /></td>
<td><input type='text' name='student[<?php echo $studentID ?>][teacherFirst]' value='<?php echo $teacherFirstname ?>' /></td>
<td><input type='text' name='student[<?php echo $studentID ?>][teacherLast]' value='<?php echo $teacherLastname ?>' /></td>
</tr>
<?php
}
// add to row
$value += 1;
}
?>
</table>
<button type="submit" name="update">Update</button>
</form>
When processing the $_POST you loop through the $_POST['student'] array and the keys will be the ids and the rest of the data is contained in the array.

Related

I get the data from mysql checkboxed it and send it back to mysql the records saves for only one student with id no 3

I get the data from mysql and display it in the table now i'm trying to send it to the database for each student by checking the checkbox, then what should i do to send all table data into the msql database with the different student id
<form class="col-md-12" action="Attendance.php" method="post">
<table id="example" class="myclass table table-striped" />
<thead>
<tr>
<th>ID</th>
<th>Full Name</th>
<th>Father Name</th>
<th><label><input type="checkbox" id="selectAll" name="chbox[]"> All Present </label></th>
</tr>
</thead>
<tbody>
<?php
$SrNo = 0;
global $dbManager;
$sql = "SELECT * FROM studentinfo";
$stmt = $dbManager->query($sql);
while($DataRows = $stmt->fetch()){
$RollNo = $DataRows['id'];
$FullName = $DataRows['fullname'];
$FatherName = $DataRows['fathername'];
?>
<tr>
<td><?php echo $RollNo; ?></td>
<td><?php echo $FullName; ?></td>
<td><?php echo $FatherName; ?></td>
<td><input type="checkbox" name="chbox[]" value="1" /></td>
</tr>
</tbody>
<?php } ?>
<tfoot>
<?php
if(isset($_POST['Submit'])){
$StudentRollNo = $RollNo;
$Attendance = $_POST['chbox'];
// date_default_timezone_set("Asia/Kabul");
$CurrentTime = time();
$DateTime = strftime("%B-%d-%Y %H:%M:%S", $CurrentTime);
if(empty($Attendance)){
$_SESSION['ErrorMessage'] = "Please filled all fields";
RedirectTo("Attendance.php");
}
else{
// the sql code is here.
global $dbManager;
foreach ($Attendance as $key => $value) {
$sql = "INSERT INTO attendance(sid, subjectid, classid, attendance, datetime) VALUES(:studentId,'1','2', :attendancE, :dateTime)";
$stmt = $dbManager->prepare($sql);
$stmt->bindValue(':studentId',$StudentRollNo);
$stmt->bindValue(':attendancE',$value);
$stmt->bindValue(':dateTime',$DateTime);
$Execute = $stmt->execute();
if($Execute){
$_SESSION['SuccessMessage'] = "Attendance Submited Successfully.";
RedirectTo("Attendance.php");
}
else{
$_SESSION['ErrorMessage'] = "Something went wrong. Try Again!";
RedirectTo("Attendance.php");
}
}
}
?>
<tr>
<td>
<i class="fa fa-check"></i>
<input type="submit" name="Submit" value="Save Attendance">
</td>
</tr>
</tfoot>
</table>
</form>
Mysql database: the problem is that the record saves only for one student.
Bring you table inside the while loop where you are fetching the values from the database and then assign the value of students dynamically for the checkbox value
you can do
value="<?php echo $RollNo; ?>";
just like you echo out the other values add the echo into the value field of the checkbox in order to get the values dynamically assigned to each checkbox

Loop through all input values

Problem
So my problem is that I have some PHP code that goes to the db and gets student data. Then the program outputs the student info onto the screen. The info is put inside an input, because the user will have the ability to edit the info. When the user edits the info and clicks on Update, I need the info to get updated on the db. My issue is that I don't how I would loop through all the inputs.
PHP Code - When user clicks Update
foreach ($_POST as $data) {
echo $data . "<br>";
}
PHP Code - Allow user to edit
<form action="server/edit/students.php" method="post">
<table>
<tr>
<th>Student ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Teacher's Firstname</th>
<th>Teacher's Lastname</th>
</tr>
<?php
// get student info
$getStudent = $link->prepare("SELECT * FROM students");
$getStudent->execute();
$getStudent = $getStudent->fetchAll(PDO::FETCH_ASSOC);
foreach ($getStudent as $student) {
$studentID = $student['studentID'];
$firstname = $student['firstname'];
$lastname = $student['lastname'];
$teacherID = $student['teacherID'];
$getTeacher = $link->prepare("SELECT * FROM teachers
WHERE teacherID = :teacherID");
$getTeacher->execute(array(
"teacherID" => $teacherID
));
$getTeacher = $getTeacher->fetchAll();
foreach ($getTeacher as $teacher) {
$teacherFirstname = $teacher['firstname'];
$teacherLastname = $teacher['lastname'];
echo "
<tr>
<td><input type='text' value='$studentID'></td>
<td><input type='text' value='$firstname'></td>
<td><input type='text' value='$lastname'></td>
<td><input type='text' value='$teacherFirstname'></td>
<td><input type='text' value='$teacherLastname'></td>
</tr>
";
}
}
?>
</table>
<button type="submit" name="update">Update</button>
</form>
So, what I did was that I used a variable to keep track of the rows of the data.
Code
<?php
// get student info
$getStudent = $link->prepare("SELECT * FROM students ORDER BY studentID");
$getStudent->execute();
$getStudent = $getStudent->fetchAll(PDO::FETCH_ASSOC);
$value = 0; // counts rows
// loop through each student
foreach ($getStudent as $student) {
$studentID = $student['studentID'];
$firstname = $student['firstname'];
$lastname = $student['lastname'];
$teacherID = $student['teacherID'];
// get teacher
$getTeacher = $link->prepare("SELECT * FROM teachers
WHERE teacherID = :teacherID");
$getTeacher->execute(array(
"teacherID" => $teacherID
));
$getTeacher = $getTeacher->fetchAll();
// loop through each teacher
foreach ($getTeacher as $teacher) {
$teacherFirstname = $teacher['firstname'];
$teacherLastname = $teacher['lastname'];
// output data
echo "
<tr>
<td><input type='text' name='studentID-$value' value='$studentID'></td>
<td><input type='text' name='firstname-$value' value='$firstname'></td>
<td><input type='text' name='lastname-$value' value='$lastname'></td>
<td><input type='text' name='teacherFirst-$value' value='$teacherFirstname'></td>
<td><input type='text' name='teacherLast-$value' value='$teacherLastname'></td>
</tr>
";
}
// add to row
$value += 1;
}
?>

How to insert multiple rows of student records scores in a while loop in a database table?

I want to create a table with input fields where student records can be inserted. The name of the students are in the first column of the table fetched from the database with a while loop. The other columns contain fields for inputing the student scores. The challenge I'm facing is how to insert the records of all the students in different row of a table called result_sec into the database. I've search for similar post but couldn't get a suitable answer. Below is the code. Thanks in advance.
<?php require('header.php'); ?>
<?php
$query_form = sprintf("SELECT * FROM regform LIMIT 2");
$form = mysqli_query($conn, $query_form) or die(mysqli_error($conn));
$formdata = mysqli_fetch_assoc($form);
if(isset($_POST['submit']))
{
$exes = $_POST['exe'];
$asss = $_POST['ass'];
$ca1s = $_POST['ca1'];
$ca2s = $_POST['ca2'];
$exams = $_POST['exam'];
foreach($exes as $key => $exe)
{
$sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam) VALUES ('$exe', '$asss[$key]', '$ca1s[$key]', '$ca2s[$key]', '$exams[$key]')";
}
$insert = mysqli_multi_query($conn, $sql);
}
?>
<form method="POST">
<table>
<thead>
<tr>
<th>Name</th>
<th>Ass.</th>
<th>Exe.</th>
<th>1st C.A.</th>
<th>2nd C.A.</th>
<th>Exam</th>
</tr>
</thead>
<tbody>
<?php do { ?>
<tr>
<td><?php echo $formdata['surname']." ".$formdata['firstname']; ?></td>
<td><input name="ass[]" size="1px"/></td>
<td><input name="exe[]" size="1px" /></td>
<td><input name="ca1[]" size="1px" /></td>
<td><input name="ca2[]" size="1px" /></td>
<td><input name="exam[]" size="1px" /></td>
<input type="hidden" name="regformid[]" value="<?php echo $formdata['regformid'];?>" />
</tr>
<?php } while ($formdata = mysqli_fetch_assoc($form)); ?>
</tbody>
</table>
<button type="submit">Insert Student Record</button>
</form>
<?php require('footer.php'); ?>
See If this resolve your problem
if(isset($_POST['submit'])){
$exes = $_POST['exe'];
$asss = $_POST['ass'];
$ca1s = $_POST['ca1'];
$ca2s = $_POST['ca2'];
$exams = $_POST['exam'];
//You can use a foreach loop to loop over one of the repeated inputs, and then use the index to access the corresponding elements in the others:
foreach ($exes as $i => $exe) {
$exee = mysqli_real_escape_string($exe);
$ass = mysqli_real_escape_string($asss[$i]);
$ca1 = mysqli_real_escape_string($ca1s[$i]);
$ca2 = mysqli_real_escape_string($ca2s[$i]);
$exam = mysqli_real_escape_string($exams[$i]);
$sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam)
VALUES ('$exee', '$ass', '$ca1', '$ca2', '$exam')";
$insert = mysqli_multi_query($conn, $sql);
}
}

Create histogram based from multiple selected checkbox

i have a list of checkboxes, right now i am able to retrieve data at database from multiple selected checkbox, and display them in a table.. below this is the code..
But my problem is how to display similar output data just like in comparetable.php to a histogram..i tried to used google chart but it just display data of a histogram exactly from the database, not getting from multiple selected checkboxes. Thank you very much for your time...
history.php
<FORM NAME ="form1" METHOD ="POST" action="comparetable.php">
<table>
<tr>
<th></th>
<th>TITLE</th>
<th>ACTION</th>
</tr>
<?php
$query = "SELECT * FROM compareresult where idmember='$idmembersession'";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($data = mysql_fetch_array($sql_query,MYSQL_ASSOC)){
$title = $data['subject'];
?>
<tr>
<td><input type="checkbox" name="selectedcheck[]"
value="<?php echo $title ?>"/></td>
<?php
echo "<td>$title</td>"
}
?>
</tr>
</table>
<INPUT TYPE = "Submit" Name = "submit1" VALUE = "COMPARE SELECTED"></form>
comparetable.php
<body>SUSTAINABILITY OF PERCENTAGE </br></br></br>
<table border='1'>
<tr>
<th>TITLE</th>
<th>PERCENTAGE RESULT</th>
</tr>
<?php
if(isset ($_POST["submit1"]))
{
$checkbox = isset($_POST['selectedcheck']) ? $_POST['selectedcheck'] : array();
foreach($checkbox as $title)
{
$query = "SELECT * FROM compareresult where subject='".$title."'";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($data = mysql_fetch_array($sql_query))
{
$result = $data['result'];
echo "<tr>";
echo "<td>".$title."</td>";
echo "<td>".$result."</td>";
echo "</tr>";
}
}
}
?>
</table></body></html>

Getting Array Value from Checkbox in PHP

I am trying to build a list where user can select any checkbox and it can send all select values for the row to the next page.
Here is what I have:
first page:
<table border="0">
<tr>
<td>Check All | Uncheck All</td>
<td>Item Name</td>
<td>Item Description</td>
</tr>
<?php
if ($num_rows == 0) {
return "No Data Found";
}else{
while ($row = dbFetchAssoc($result)) {
$item_id = $row['item_id'];
$item_name = $row['item_name'];
$item_desc = $row['item_desc'];
$item_qty = $row['item_qty'];
$item_upc = $row['item_upc'];
$item_price = $row['item_price'];
$vendor_id = $row['vendor_id'];
?>
<tr>
<td> <input type="checkbox" name="area[]" value="<?=$item_id?>" /></td>
<td><input type="text" name="item_name[]" value="<?=$item_name?>"></td>
<td><input type="text" name="item_desc[]" value="<?=$item_desc?>"></td>
</tr>
<?php
}
}
?>
<tr><td colspan="3"><input type="submit"></td></tr>
</table>
</form>
Next Page:
<table>
<tr><td colspan="3"><?php "Total Item(s) selected: "; echo count($_POST['area']); ?></td></tr>
<?php
if(!empty($_POST['area'])) {
foreach($_POST['area'] as $check) {
echo "<tr><td>".$check."</td><td>".$_POST['item_name']."</td><td>".$_POST['item_name']."</td></tr>";
}
}
?>
</table>
I need to read the item_name and item_desc value as well. How do I get it?
You need the key:
if(!empty($_POST['area'])) {
foreach($_POST['area'] as $key => $check) {
echo "<tr><td>".$check."</td><td>".$_POST['item_name'][$key]."</td><td>".$_POST['item_desc'][$key]."</td></tr>";
}
}
As Marc said in his answer it would probably be better to set key's in your loop creating the input.
<?php
if ($num_rows == 0) {
return "No Data Found";
}else{
$counter = 0;
while ($row = dbFetchAssoc($result)) {
$counter++;
$item_id = $row['item_id'];
$item_name = $row['item_name'];
$item_desc = $row['item_desc'];
$item_qty = $row['item_qty'];
$item_upc = $row['item_upc'];
$item_price = $row['item_price'];
$vendor_id = $row['vendor_id'];
?>
<tr>
<td> <input type="checkbox" name="area[<?=$counter?>]" value="<?=$item_id?>" /></td>
<td><input type="text" name="item_name[<?=$counter?>]" value="<?=$item_name?>"></td>
<td><input type="text" name="item_desc[<?=$counter?>]" value="<?=$item_desc?>"></td>
</tr>
<?php
}
}
?>
foreach($_POST['area'] as $key => $check) {
echo $check . $_POST['item_name'][$key];
}
assuming that there's an exact 1:1 correspondence between your three submitted arrays. Remember that checkboxes which are NOT checked do NOT get submitted with the form, so this is most likely NOT true and this code will not work as written.

Categories