So i've created an administration page that creates X-number of forms based on how many users we have in our database, each of which have a submit button next to them to submit changes to the dates we have in our DBs. My problem is that when I want to get the value of what gets posted I can't extract exactly what I need from what gets posted. It gets saved into an array called and when I print_r the array I get exactly what I want, which is:
[1] => "whatever date they typed in"
(obviously the 1 changes depending on which item they changed the date of)
I need be able to query my datebase by:
UPDATE users SET subdate="whatever they typed in" WHERE id="the array reference number"
I know exactly what I need to do, I'm just not as familiar with SQL as i'd like to be, so any help would be greatly appreciated. Thanks in advance.
Code for reference:
<div class="form-section grid12" id="changedates">
<h1>Change Dates</h1>
<?php
$query = mysql_query("SELECT * FROM users WHERE admin='y'");
?>
<table>
<?php
while($row = mysql_fetch_assoc($query)) {
?>
<tr>
<td>
<h5><?php echo $row['displayname'];?></h5>
</td>
<td>
<form action="" method="POST">
<input type="text" name="subdate[<? echo $row['id'] ?>]" value="<?php echo $row['submissiondate'];?>">
<input type="text" name="nextupdate[<? echo $row['id'] ?>]" value="<?php echo $row['nextupdate'];?>">
</td>
<td>
<input type="submit" value="Set Date" name="setdate">
</form>
</td>
<?php
}
?>
</table>
</div>
You could use foreach...
foreach ($_POST[nextupdate] as $rowId => $time)
{
// do db update
}
Edit: Just realised you have more than one input per form.
Why not name each input with an array name:
<input type="text" name="form_data[<?= $row_id ?>][subdate]">
<input type="text" name="form_data[<?= $row_id ?>][nextupdate]">
In PHP:
foreach ($_POST[form_data] as $rowId => $values)
{
$subdate = $values[subdate];
$nextupdate = $values[nextupdate];
// do SQL stuff
}
Related
Inserting multiple record in phpmyadmin att table keeping all the information same except attendance and student id after clicking the submit button.Its taking only one last row without attendance status.I'm fetching attendance sheet from database.I have been stuck here in my first php project.
faculty panel
<form action="<?php $PHP_SELF ?>" method="post">
<li><b>Select Courses :</b> <select name="courses" id="courses" class="form-
control action" >
<option value="">Courses</option>
<?php echo $courses; ?></select></li><br/>
<li><b>Select Semesters :</b> <br><select name="semesters" id="semesters"
class="form-control action" >
<option value="">Semesters</option></select></li><br/>
<li><b>Select Subjects :</b><br> <select name="subjects" id="subjects"
class="form-control " >
<option value="">Subjects</option></select>
<br/>
<li><b>Session No:<b><br/><input type="text" name="session_no"
id="session_no" placeholder ="Session No" class="form-control">
<br>
<label class="control-label" for="date">Date</label>
<br/>
<input class="form-control" id="date" name="date" placeholder="DD/MM/YYYY"
type="date"/>
<br/>
<li><b>Enter time:</b></li><br/>
From :<input type="time" name="time_from" id="time_from" class="form-
control"/> </li><li>
<br/>
To :<input type="time" name="time_to" id="time_to" class="form-control"/>
</li></div>
<br>
<li><label class="btn btn-info">Display attendance sheet</label> </li>
<br/>
//attendance table
<table id = "table" class = "table table-bordered">
<thead class = "alert-info">
<tr>
<th>Student ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<?php
$q_student = $conn->query("SELECT * FROM `student`")
or die(mysqli_error());
while($f_student = $q_student->fetch_array()){
?>
<tr>
<td><input name="student_no" value="<?php echo
$f_student['student_no']?>" class="form-control"
readonly/></td>
<td><?php echo $f_student['firstname']?></td>
<td><?php echo $f_student['lastname']?></td>
<td><input type="radio" name="attendance[<?php echo
$f_student['student_no']; ?>]" value="1"
class="form-control"></td>
<td><input type="radio" name="attendance[<?php echo
$f_student['student_no']; ?>]" value="0"
class="form-control"></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
//Insert Record into attendancetable
if(isset($_POST['submit']))
{
foreach ($_POST['attendance'] as $attendance){
$faculty_id =
mysqli_real_escape_string($conn,$_SESSION['faculty_id']);
$student_no =
mysqli_real_escape_string($conn,$_POST['student_no']);
$courses = mysqli_real_escape_string($conn,$_POST['courses']);
$semesters = mysqli_real_escape_string($conn,$_POST['semesters']);
$subjects = mysqli_real_escape_string($conn,$_POST['subjects']);
$session_no = mysqli_real_escape_string($conn,$_POST['session_no']);
$date = mysqli_real_escape_string($conn,$_POST['date']);
$time_from = mysqli_real_escape_string($conn,$_POST['time_from']);
$time_to = mysqli_real_escape_string($conn,$_POST['time_to']);
$attendance=var_dump($_POST['attendance']);
$conn=mysqli_connect("localhost","root","","db_sars");
$ins="INSERT INTO att( faculty_id,student_no,courses,semesters,subjects,session_no,date,time_from,time_to,attendance_status)
VALUES ('$faculty_id','$student_no','$courses','$semesters','$subjects','$session_no','$date','$time_from','$time_to','$attendance')";
}
if(#mysqli_query($conn,$ins))
{
echo "inserted";
}
else
{
die(#mysqli_error());
}
}
?><input type="submit" name="submit" value="Submit Form" class="btn btn-info"></form>
In the code you posted, you are not assigning the attendance data ($_POST['attendance']) to the $attendance variable due to use of var_dump.
You wrote:
$attendance=var_dump($_POST['attendance']);
From the php manual for var_dump:
Return Values
No value is returned.
Instead, try formatting this line like you did all the rest:
$attendance = mysqli_real_escape_string($conn,$_POST['attendance']);
Adding multiple students at a time- update
It appears that you are printing each student id in the front end table. I think that would be a better field to loop with. However, with your current front end code, it is creating a new post variable for each student id. Instead you probably want this instead:
<td><input name="student_no" value="StudentID[<?php echo $f_student['student_no']?>]" class="form-control" readonly/></td>
Note how this turns the student id into an array of student ids rather than a ton of different variables of each student ID.
Then for your foreach:
foreach ($_POST['StudentID'] as $StudentID) {
$StudentID is now updated for each iteration and allows you to look up the appropriate index in the other arrays. And you would change the pertinent rows as:
$student_no = mysqli_real_escape_string($conn,$StudentID); // The student ID is set by as in foreach
$StudentAttendance = $_POST['attendance'][$StudentID]; // Get the attendance status by looking up the student by student id in the attendance array
$attendance=mysqli_real_escape_string($conn,$StudentAttendance); // Escape input to avoid table disasters (reference Little Bobby Tables)
I haven't tested your code and understand that there is a lot more going on than this. However, it's probably best to tackle one thing at a time. What you have to do is create a loop to go over each student, and each field that you want to collect should be posted as an array with an index for each student by their student id.
Using var_dump is useful for understanding what a variable contains (for instance, it would help us to see what your variables contain if you would post the var_dump output with your question). If you have error messages, please post them as it helps guide us in the right direction as we attempt to help you out.
This is the code for the admin panel of a certain site. Appointments asked by customers will be shown in this page. The admin will be able to change the appointments based on availability.
<?php
while($row = mysqli_fetch_assoc($result)){
?>
<form action="adminEdit.php" method="POST">
<tr>
<td><input type="text" id="name" value="<?php echo $row['Name'];?>"></input></td>
<td><input type="text" id="address" value="<?php echo $row['Address'];?>"></input></td>
<td><input type="text" id="phone" value="<?php echo $row['Phone'];?>"></input></td>
<td><input type="text" id="license" value="<?php echo $row['Car_License_No'];?>"></input></td>
<td><input type="text" id="engine" value="<?php echo $row['Car_Engine_No'];?>"></input></td>
<td><input type="text" id="date" value="<?php echo $row['Date'];?>"></input></td>
<td><input type="text" id="mechanic" value="<?php echo $row['Mechanic'];?>"></input></td>
<td><input type="submit" name="submit" value="Change"/></td>
</tr>
</form>
<?php
}
?>
Here, each row of data has a corresponding button which will be used for changing or modifying the records of that particular row. Once the admin changes a specific appointment it should get updated in database.
My problem is, all the rows are getting generated by a while loop. Now how can I access a specific row when the change button of that specific row has been clicked ? As the rows are getting generated by a loop, I wont be able to access them bynameoridbecause all of them will have the samenameandid`.
Searched for relevant questions but none of them matched with my scenario. It will be of great help getting an answer. Thanks in advance.
Personally I'd be inclined to take the output from being in the loop for better control over the data and resolving the issue. You're also creating a new form on each loop.
Just loop the DB and create a new variable, then use that variable to output the data in the form.
Example code to show the basic idea, not tested or stating it's complete etc:
while ($row = mysqli_fetch_assoc($result)) {
$someNewVar[$row['id']] = $row;
// The 'id' index would be from DB which identifies individual rows
}
?>
<form action="adminEdit.php" method="POST">
<?php
foreach ($someNewVar as $index => $value) {
?>
<tr>
<td>
<input
type="text"
id="<?php echo $index;?>"
value="<?php echo $value['Name'];?>">
</input>
</td>
<td>
<input
type="submit"
name="submit"
value="Change"/>
</td>
</tr>
<?php
}
?>
</form>
Then you'd need to have the row ID passed from clicking the submit button.
On a side note, this whole approach could be tidied up, and data should be obtained in one file separate to where you output it.
Then in the file which obtains the data you can set the array to something which is also identified in the output file to manage if no data was obtained.
ie
getData.php
while ($row = mysqli_fetch_assoc($result)) {
$dataFromDb[$row['id']] = $row;
}
$someNewVar = !empty($dataFromDb) ? $dataFromDb : false;
showData.php
if ($someNewVar) {
// do the loop and form
} else {
echo 'sorry no data found';
}
So i have a table, that I load checkbox values into. Once the checkboxes are clicked, I use a submit button to save them into a database. However at the moment I can only Save one row at a time? I need to be able to save all clicked checkboxes into the datbase
For example i have 5 rows. If the checkboxes on row 2 and 3 are checked then they should be saved into the database however right now only the last clicked(row 3) are being saved into the database.
Heres my code so far
Php connect code
<?php
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query->select($db->quoteName(array('CV_ID', 'Classifier', 'Value')));
$query->from($db->quoteName('classvalues'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
?>
Loading table with checkboxes code
<form name="names" id="names" action="<?php echo JURI::current(); ?>" method="post">
<table border="5",th,td, cellspacing="5", cellpadding="5", width="500", align="left">
<tr>
<th>CV_ID</th>
<th>Classifier</th>
<th>Level</th>
</tr>
<?php foreach ($results as $row): ?>
<tr>
<td> <input type="checkbox" id="chk113" name="CV_ID" value="<?php echo $row->CV_ID ?> "/>
<label for="chk113"><?php echo $row->CV_ID ?> </label> </td>
<td> <input type="checkbox" id="chk111" name="Classifier" value="<?php echo $row->Classifier ?>"/>
<label for="chk111"><?php echo $row->Classifier ?></label> </td>
<td> <input type="checkbox" id="chk112" name="Value" value="<?php echo $row->Value ?>"/>
<label for="chk112"><?php echo $row->Value ?></label> </td>
</tr>
<?php endforeach ?>
</table>
<p><input id="submit" name="submit" type="submit" value="Submit Names" /></p>
</form>
Saving
?>
<?
if( (isset($_POST['CV_ID'])) || (isset($_POST['Classifier'])) || (isset($_POST['Value'])) ) {
//first name or last name set, continue-->
$CV_ID = $_POST['CV_ID'];
$Classifier= $_POST['Classifier'];
$Value= $_POST['Value'];
$db =& JFactory::getDBO();
$query = "INSERT INTO SessionTa (CV_ID, Classifier, Value) VALUES ('".$CV_ID."','".$Classifier."','".$Value."');";
$db->setQuery( $query );
$db->query();
} else {
}
?>
each checkbox in your form appears to have the same name. Trying naming them as an array, e.g.
<input type="checkbox" id="chk113" name="CV_ID[]" value="<?php echo $row->CV_ID ?> "/>
Notice the extra '[]'. At that point, you can print_r($_POST) in your saving php file to see the differences. Your db update logic might need to be tweaked as a result
I have a form with rows which are populated from a table. Each row has a "checkbox" which the user can check or not.
When the form is submitted I want to be able to read which checkbox have been selected and insert the result in to a data table.
My code so far
FORM:
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
<table
<?php do { ?>
<tr>
<td>input type="text" name="InspectRoomNo" value="<?php print $row_InspectItems['AuditItemNo']; ?>"></td>
<td>php echo $row_InspectItems['AuditItem']; ?>td>
<td>input name="check[]" type="checkbox" ></td>
</tr>
<?php } while ($row_InspectItems = mysql_fetch_assoc($InspectItems)); ?>
<input type="submit" value="Insert record">
</table>
The insert: fetchs $Items from table
while($row = mysql_fetch_assoc($Items))
{
$array[] = $row['AuditItem'];
}
foreach($array as $id) {
$AuditItemID = mysql_real_escape_string($id);
if(isset($_POST['check'])){
$Checked = mysql_real_escape_string($_POST['check'][$row]);
}
}
The problem I am having is the returned values for all the checkbox is true, even if a checkbox was not selected.
Can anyone help me sort this issue.
Many thanks.
Do it like this:
if(!empty($_POST['check'])) {
foreach($_POST['check'] as $check) {
echo $check;
}
}
You should put the item id inside the checkbox name:
<td><input name="check[<?= $row_InspectItems['AuditItem']; ?>]" type="checkbox" /></td>
Then, you can simply iterate over it:
foreach ($_POST['check'] as $id => $value) {
// do stuff with your database
}
I'm assuming than whomever runs this script is trusted, because it would be easy to forge the list of ids; make sure the current user has permissions to update those records.
What is happening, is that only selected checkboxes get sent to the server, so you will see that your $_POST['check'] array (this is an array!) is smaller than the number of items you have displayed on the screen.
You should add your ID's so that you know what checkboxes got checked and adapt your php processing code to handle an array instead of a single value.
You are also overwriting your InspectRoomNo every row, so you should use an array there as well.
The form side would look something like:
<td><input type="text" name="InspectRoomNo[<?php echo row_InspectItems['AuditItemNo']; ?>]" value="<?php print row_InspectItems['AuditItemNo']; ?>"></td>
<td><?php echo $row_InspectItems['AuditItem']; ?></td>
<td><input name="check[<?php echo row_InspectItems['AuditItemNo']; ?>]" type="checkbox" ></td>
I am setting up a form using this PHP that loops through all records a user may have:
<?php foreach ($items as $row): ?>
<tr>
<td>
<?php echo form_hidden('id', $row->id); ?>
</td>
<td>
<?php echo '<strong>' . $row->name . '</strong>'; ?>
</td>
<td>
<?php echo form_input('number', $number); ?>
</td>
<td>
<?php echo form_input('registry', $registry); ?>
</td>
<td>
<?php echo form_checkbox('OK', $ok, $ok); ?>
</td>
</tr>
<?php endforeach; ?>
This gives me a form with the following look:
The idea here is that each row belongs to a unique ID/row in the database, and I would like to allow the user to edit all on the same page/form, using a single submit button.
What would be the best way of implementing this?
When this data is submitted, there should be a way of looping through each packet of information (from each user) in my controller. Would this be done via ajax/json?
This does not use codeigntier, but you should be familiar with the general technique before attempting to use CI to shortcut this process. Codeigniter will help you with rendering the form elements, performing validation, escaping your input and performing your query - but it will only help you (do anything) if you understand the basic principles involved. Hope this helps
MARKUP
<form action="/process.php">
<div>
<h2>GORDON</h2>
<input type="text" name="user[1][number]" /> <!-- The number corresponds to the row id -->
<input type="text" name="user[1][registry]" />
<input type="checkbox" name="user[1][ok]" value="1" />
</div>
<div>
<h2>ANDY</h2>
<input type="text" name="user[242][number]" />
<input type="text" name="user[242][registry]" />
<input type="checkbox" name="user[242][ok]" value="1" />
</div>
<div>
<h2>STEWART</h2>
<input type="text" name="user[11][number]" />
<input type="text" name="user[11][registry]" />
<input type="checkbox" name="user[11][ok]" value="1" />
</div>
<input type="submit" />
PHP
$users = $_REQUEST['user'];
foreach ($users as $rowId => $info){
// YOU SHOULD MAKE SURE TO CLEAN YOUR INPUT - THIS IS A GUESS AT WHAT YOUR DATA TYPES MIGHT BE
$id = (int) $rowId;
$number = (int) $info['number'];
$registry = mysql_real_escape_string($info['registry']);
$ok = (int) ($info['ok']);
$q = "UPDATE user SET number = $number, registry = '$registry', ok = $ok WHERE id = $id";
mysql_query($q);
// You may want to check that the above query was sucessful and log any errors etc.
}
There's no need to use ajax mate.
For each put a hidden input with the ID of the row in this format:
<input type="hidden" name="id[<?= $row->id ?>]" value="<?= $row->id ?>" ?>
Do the same for each element in the tr, i.e. name them as
name="number[<?= $row->$id ?>]"
name="registry[<?=$row->$id ?>]"
name="ok[<?=$row->$id ?>]"
and once you post the FORM you can iterate each row with:
foreach ($_POST['id'] as $key => $value) {
echo $_POST['name'][$key];
}
You need to set up input-names as array-names, so you will send the whole form and may iterate over the entries.
e.g.
<?php
echo form_input('userdata[' . $row->id . '][number]', $number);
?>
which would possibly create an
<input name="userdata[1][number]" />
(I don't know where those form-functions came from…)
This will result in an array $_POST['userdata'] which may be iterated via:
foreach($_POST['userdata'] as $userId => $userInputFields)
{
$user = new User($userId);
$user->number = $userInputFields['number'];
// …
}