How to update data in MYSQL using foreach loop - php

I am doing attendance management system but I am unable to understand. please help me
<form method="post">
<div class="table-responsive py-4">
<table class="table table-flush" id="datatable-basic">
<thead class="thead-light">
<tr>
<th>Name</th>
<th>Father's Name</th>
<th>Hall Ticket</th>
<th>Department</th>
<th>Attendace</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_POST["search_students"])){
$department=$_POST['department'];
$sql = "SELECT * FROM student_info WHERE department='$department'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["father_name"]."</td>";
echo "<td>".$row["hall_ticket"]."</td>";
echo "<td>".$row["department"]."</td>";
echo "<td>
Present <input type='radio' name='attendance[".$row['hall_ticket']."][".$row['department']."]' value='Present'>
Absent <input type='radio' name='attendance[".$row['hall_ticket']."][".$row['department']."]' value='Absent'>
</td>";
echo "</tr>";
}
}
}
?>
</tbody>
</table>
</div>
<div class="col-lg-12 mb-3">
<button type="submit" name="mark_attendance" class="btn btn-success">Mark Attendance</button>
</div>
</form>
</div>
<?php
if(isset($_POST["mark_attendance"])){
$attendance=$_POST['attendance'];
foreach ($attendance as $key => $value) {
if($value=="Present") {
$query="Insert into attendance (hall_ticket,attendance) values ('$key','Present')";
$insertAttendance=$conn->query($query);
}
else {
$query="Insert into attendance (hall_ticket,attendance) values ('$key','Absent')";
$insertAttendance=$conn->query($query);
}
}
if($insertAttendance){
echo "Attendance Updated Sucessfully";
}
}
?>
</div>
Here i want 2 key to store into my database as hall ticket value and department value.
attendance[".$row['hall_ticket']."][".$row['department']."]
how to use both variables to store into my db. I want to store each table person attendance with their department and hallticket. i will get the hallticket if i remove department from name and simply use $key to store the values.

Try following code:
HTML Code (Created dummy data for reference):
<form action='new.php' method="POST" >
Presnt<input type="radio" name="attendance[111][555]" value="present"><br>
Absent<input type="radio" name="attendance[111][555]" value="absent"><br><br>
Presnt<input type="radio" name="attendance[222][555]" value="present"><br>
Absent<input type="radio" name="attendance[222][555]" value="absent"><br><br>
Presnt<input type="radio" name="attendance[333][555]" value="present"><br>
Absent<input type="radio" name="attendance[333][555]" value="absent"><br>
<input type="submit">
</form>
PHP Code:
<?php
$attendance=$_POST['attendance'];
$data = "";
foreach ($attendance as $key => $value) {
$department = array_keys($value)[0];
$data.="('". $key ."','". $department ."', '" . $value[$department] . "'),";
}
$query = "INSERT INTO attendance (hall_ticket,department,attendance) VALUES " .
rtrim($data, ",");
// Your Query will look like:
// Query = "INSERT INTO attendance (hall_ticket,department,attendance)
// VALUES ('111','555', 'present'),
// ('222','555', 'present'),
// ('333','555', 'absent')";
// Now execute your query
$conn->query($query);
echo $sql;
?>
Note :
Never hit the database in for loops
Even this code will work for you but this is open for SQL injection, you should use a prepared statement to build and execute you query.

so you $attendance is
$attendance=array(
$row['hall_ticket'] => array(
$row['departement']"=> [" present " OR "absence"]
);
this what i understand
my solution is
foreach ($attendance as $hall => $departements) {
foreach($departements as departement => $value){
$req="INSERT INTO attendance (hall_ticket,department,attendance)
values ('".$hall. "','". $departement ."' ,'". $value ."')";
$insertAttendance=mysqli_query($dataBaseConnect,$req);
}

Related

Multiple Choice Quiz - not updating responses

I have a form that outputs:
Quiz_Assign_ID (Combines User_ID with Quiz ID)
Question ID
Checkboxes for inputting the response (Option A, Option B, Option C)
<div class="Main">
<form method="post" action="LP_Quiz_Student_Quiz_Responses.php">
<?php
$quiz_id = trim($_GET['quiz_id']);
$quiz_assign_id = trim($_GET['quiz_assign_id']);
$i = 1;
$count=1;
$sel_query=("SELECT Quiz.quiz_id, Quiz.quiz_title, Quiz_Questions.quiz_id, Quiz_Questions.quiz_question_id, Quiz_Questions.question, Quiz_Questions.option1, Quiz_Questions.option2, Quiz_Questions.option3, Quiz_Questions.answer FROM Quiz, Quiz_Questions WHERE (Quiz.quiz_id=Quiz_Questions.quiz_id) and (Quiz.quiz_id=?)");
$stmt = $conn->prepare($sel_query);
$stmt->bind_param("i", $quiz_id);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
if($result->num_rows === 0) exit('No Quiz Questions!');
while($row = $result->fetch_assoc()) { ?>
<p></p>
<p> </p>
<table>
<tr>
<td>
</td>
<td>
<input name="quiz_assign_id" type="hidden" value=" <?php echo $quiz_assign_id; ?>" /> <input name="quiz_question_id" type="hidden" value=" <?php echo $row["quiz_question_id"]; ?>" /></td>
<td> </td>
</tr>
<tr>
<td>
<h4>Question <?php echo $i++; ?> </h4>
</td>
<td>
<h4><?php echo $row["question"]; ?> </h4>
</td>
<td> </td>
</tr>
<tr>
<td>
<h4>A</h4>
</td>
<td><?php echo $row["option1"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option A" style="width: 20px" /></td>
</tr>
<tr>
<td>
<h4>B</h4>
</td>
<td><?php echo $row["option2"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option B" /></td>
</tr>
<tr>
<td>
<h4>C</h4>
</td>
<td><?php echo $row["option3"]; ?> </td>
<td>
<input name="Response[<?php echo $quiz_question_id; ?>]" type="checkbox" value="Option C" /></td>
</tr>
</table>
<?php
}
?>
<input name="Submit1" type="submit" value="submit" />
</form>
</div>
Upon submission I run the following script, which captures the response but does not get the question_id and Quiz_Assign_ID and does not update the values in the database:
<?php
if(!empty($_POST['Response'])) {
foreach ($_POST['Response'] as $value) {
$quiz_assign_id=trim($_POST['quiz_assign_id']);
$quiz_question_id=$_POST['quiz_question_id'];
echo 'Answer'; echo $value;
echo 'Question:'; echo $quiz_question_id;
echo 'Student ID'; echo $quiz_assign_id; echo 'successfully assigned! <br>';
$stmt = $conn -> prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
if (
$stmt &&
$stmt -> bind_param('sss', $value, $quiz_assign_id, $quiz_question_id) &&
$stmt -> execute() &&
$stmt -> affected_rows === 1
) {
echo "<script>
alert('Responses submitted!');
window.history.go(-2);
</script>";
} else {
echo"<script>
window.history.go(-2);
</script>";
}
}
}
?>
I have been playing with it for hours, but with no luck.
Because you are using check boxes en not radio buttons, you should change your input checkbox name attribute, so it's sending a nested array with the question ID as a key and the answers array as the value, like so: (notice the extra []) Also $quiz_question_id is not defined, you should use the $row array.
<input name="Response[<?php echo $row['quiz_question_id']; ?>][]" type="checkbox" value="Option A" style="width: 20px" /></td>
Because the response array is now nested, the question answers are grouped by question_id. To iterate over the nested response array, use the following for loop:
foreach ($_POST['Response'] as $question_id => $answered) {
echo "Question ID:".$question_id."<br />";
// iterate answers
foreach ($answered as $answer) {
echo "Answered: ".$answer."<br />";
}
// Or transform to comma separated string
echo "Answered: ".implode(", ", $answered)."<br />";
}
So your LP_Quiz_Student_Quiz_Responses.php could look like this:
if(!empty($_POST['Response'])) {
$done = 0;
foreach ($_POST['Response'] as $quiz_question_id => $values) {
$quiz_assign_id = trim($_POST['quiz_assign_id']);
echo 'Answers'; print_r($values); // Values is an array here.
echo 'Question:'; echo $quiz_question_id;
echo 'Student ID'; echo $quiz_assign_id; echo 'successfully assigned! <br>';
// Because $values is an array, transform it into a comma separated string to insert them into the database
// But you could also make a database table with answers and loop over the $values array.
$value = implode(', ', $values);
$stmt = $conn->prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
$stmt->bind_param('sss', $value, $quiz_assign_id, $quiz_question_id);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$done++;
}
}
echo "<script>";
if ($done) {
echo "alert('Responses submitted!');";
}
echo "window.history.go(-2);";
echo "</script>";
}
To accommodate both type of questions with check boxes and questions with radio buttons, you can use the same response code, but first check if its an array before transforming it into a string.
Questions with radio buttons, one answer per question possible:
<input name="Response[<?php echo $row['quiz_question_id']; ?>]" type="radio" value="Option A" style="width: 20px" /></td>
Questions with check boxes, multiple answers per question possible:
<input name="Response[<?php echo $row['quiz_question_id']; ?>][]" type="checkbox" value="Option A" style="width: 20px" /></td>
And now your LP_Quiz_Student_Quiz_Responses.php could look like this:
if(!empty($_POST['Response'])) {
$done = 0;
foreach ($_POST['Response'] as $quiz_question_id => $values) {
$quiz_assign_id = trim($_POST['quiz_assign_id']);
// If it's an array (checkbox), transform to string.
// Else it is already a string (radio).
if (is_array($values)) {
$values = implode(', ', $values);
}
$stmt = $conn->prepare('UPDATE Quiz_Assign_Student_Question SET response = ? WHERE quiz_assign_id = ? and quiz_question_id =? ');
$stmt->bind_param('sss', $values, $quiz_assign_id, $quiz_question_id);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$done++;
}
}
echo "<script>";
if ($done) {
echo "alert('".$done." Responses submitted!');";
}
echo "window.history.go(-2);";
echo "</script>";
}
But with above code you can accommodate all kind of field types.
To put it simple:
foreach ($_POST['Response'] as $question_id => $answered) {
echo "Question ID:".$question_id."<br />";
// Check if array, it's a checkbox or multiple select question
if (is_array($answered)) {
// iterate answers
foreach ($answered as $answer) {
echo "Answered: ".$answer."<br />";
}
// Or transform to comma separated string
echo "Answered: ".implode(", ", $answered)."<br />";
} else {
// radio, hidden, input, select or textarea question
echo "Answered: ".$answered."<br />";
}
}
I hope this points you in the right direction.

PHP Array input name to database

I am working on a hotel feature page.
the peice of code I am stuck on is the following:
<?php
$result = mysqli_query($conn, "select * from facilities_type");
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<th scope="row">
<input class="form-check-input" type="checkbox" id="blankCheckbox" name="room_feature_cb[]" value="<?php echo $row["facilitiestype_id"]; ?>">
</th>
<td>
<?php echo $row["room_facilities"] ?>
</td>
<td>
<img src="upload-img/icon/<?php echo $row["facilities_icon"]; ?>" width="25">
</td>
</tr>
<?php
}
?>
I want to save the data by using the array, but i cannot get the name to save into the database
if (isset($_POST["room_feature_savebtn"]))
{
$feature = $_POST['room_feature_cb'];
for($result=0;$result>$feature;$result++)
{
mysqli_query($conn,"insert into facilities_details(facilitiestype_id) value ('$feature')");
}
}
You can use the foreach, is a better option in this case:
if (isset($_POST["room_feature_savebtn"]))
{
$features = $_POST['room_feature_cb'];
foreach ($features as $feature) {
mysqli_query($conn, "insert into facilities_details(facilitiestype_id) value ('$feature')");
}
}
Your error is when make a for you dont use the index of array ($result) that create in this, try with:
if (isset($_POST["room_feature_savebtn"]))
{
$feature = $_POST['room_feature_cb'];
for($result=0; $result < $feature; $result++) {
mysqli_query(
$conn,
"insert into facilities_details(facilitiestype_id) value ('" . $feature[$result] . "')"
);
}
}
I recomend the foreach

MYSQL column select based on checkbox and group by checkbox

I am trying to select columns from a mysql table based on checkboxes (columns provided as check boxes). The following is a reproducible example.
<?php
require('connect.php');
?>
<!DOCTYPE html>
<head></head>
<body>
<div>
<form action="" method="POST">
<input type="checkbox" name="check_list[]" value="ZONE"><label>ZONE</label>
<input type="checkbox" name="check_list[]" value="STATE"><label>STATE</label>
<input type="submit" name="submit" Value="Submit"/>
</form>
</div>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
$checkboxes = isset($_POST['check_list']) ? $_POST['check_list'] : array();
foreach($checkboxes as $value) {
echo $value,','; //selected value
$sql = "SELECT $value,sum(RICEPDS) as 'CEREALS' from ck group by $value" ;
$result = mysqli_query($connection, $sql);
}}}
?>
<div>
<table>
<thead>
<tr>
<?php
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysqli_num_fields($result);
for($i=0; $i<$fields_num; $i++)
{
$field = mysqli_fetch_field($result);
echo "<th>{$field->name}</th>";
}
?>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<?php
foreach($row as $cell)
echo "<td>$cell</td>";
?>
</tr>
<?php
}
mysqli_free_result($result);
?>
</tbody>
</table>
</div>
</body>
</html>
Understandably when I select one checkbox the table gets returned. When I select both the checkboxes, I am getting the error message echoed from this: die("Query to show fields from table failed");.
I think I have to get the last trailing comma from the $value. How do I do it?
Refer this link PHP mysqli_multi_query() Function https://www.w3schools.com/php/func_mysqli_multi_query.asp
Taking inspiration from this post I resolved this issue. My working code is as follows:
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
$my_values = implode(",", $_POST['check_list']);
$sql = "SELECT $my_values,sum(RICEPDS) as 'CEREALS' from ck group by $my_values" ;
$result = mysqli_query($connection, $sql);
}}

Populating html table with database data through user selection in php

So, I have a checkbox that allows the user to select the columns they want to view. So, if the user wants for example to select only 2 columns (say, TicketID and Category) it will only show the data of the ID and the category of the ticket. Here's what I have so far:
form:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<ul>
<li><input type="checkbox" name="filter[]" value="TicketID" >Ticket ID</li>
<li><input type="checkbox" name="filter[]" value="Category" />Category</li>
<li><input type="checkbox" name="filter[]" value="Priority" />Priority</li>
<li><input type="checkbox" name="filter[]" value="Status" />Status</li>
<li><input type="checkbox" name="filter[]" value="InitialDescription" />Initial Description</li>
<li><input type="checkbox" name="filter[]" value="SubmittedDate" />Submitted Date</li>
<li><input type="checkbox" name="filter[]" value="Description" />Status Description</li>
<input type="submit" value="Refresh Filters">
</ul>
</form>
</td>
<td>
<?php
viewTicketTable($_SESSION['userID'],$_POST['filter']);
?>
viewticketTable function:
function viewTicketTable($userID,$columns) {
/* Accepts $userID which will identify the tickets related with the user and
$columns which will filter only the columns that are required and outputs the
table with the columns passed through. */
/*
$columns_array = explode(',', $columns);
foreach($array as $array){
echo $array;
} */
foreach($columns as $filter) {
$filter = $filter . ',' ;
}
$filter = substr($filter, 0, -1);
$query = mysql_query("
SELECT $filter
FROM Ticket
LEFT JOIN TicketHistory
ON Ticket.TicketID = TicketHistory.TicketID
WHERE CustomerID = $userID;
");
/* Creation of the table */
echo '
<table border="1">
<thead>
<tr>';
foreach($columns as $tableHeader) {
$tableHeader = '<th scope="col">' . $tableHeader . '</th>' ;
echo $tableHeader;
}
echo '
</tr>
</thead>
<tbody>
';
/*Looping through the script to print out all the information.*/
while ($row = mysql_fetch_array($query) or die(mysql_error())) {
echo '
<tr>';
foreach($columns as $field) {
echo '<td>' . $row[$field] . '</td>';
}
echo '</tr>
';
}
echo ' </tbody>
</table>';
}
The problem resides in the while loop. row[$field] is only populating the last column instead of populating all of them. Any help?
You have an error in your SQL syntax - you have an extra ; before the " closes
Also, you should use mysql_fetch_assoc in place of mysql_fetch_array as using mysql_fetch_array without specifying a method is going to return a double array.
I fixed it. I'll post the answer in case someone has the same issue.
The problem was fixed here:
$filter = "";
foreach($columns as $c) {
$filter = $filter . $c . ',' ;
}
$filter = substr($filter, 0, -1);
The loop was not assigning the values to the $filter variable so I had to create an external variable. There was also anther error in the foreach loop that I had to fix with an if statement (not the best way of doin it, but it works):
foreach($columns as $field) {
if ($field == 'Ticket.TicketID'){
$field = 'TicketID';
}
echo '<td>' . $row[$field] . '</td>';
}
Ticket.TicketID wasn't accepted in the $row array, so I had to change it to TicketID
Thanks everyone for the help anyway.

Check a check box if it's value is in DB. PHP

I have a loop of checkboxes from a MySql table "exercise" in a form as shown below:
<form id="form1" name="form1" method="POST" action="insertDrills.php">
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<?php do { ?>
<tr>
<td>
<input type="checkbox" name="drillSelect[]" value="<?php echo $row_Recordset1['drillID']; ?>" id="drillSelect" />
<?php echo $row_Recordset1['rubrik']; ?>
</td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
<tr>
<td colspan="2">
<input name="spelarID" type="hidden" id="spelarID" value="<?php echo $row_rsSpelare['id']; ?>" />
<input name="date" type="hidden" id="date" value="<? print date("Y-m-d h:i:s"); ?>" />
<input type="submit" name="submit" id="submit" value="Välj övningar" />
<input type="button" value="Avbryt" onclick="window.close();"></button>
</td>
</tr>
</table>
</form>
The value from the hidden fied "spelarID" along with the value from the checkbox array are inserted to a look-up table "exercise_spelare_ref" with this:
<?php
$id = $_POST['spelarID'];
$drills = $_POST['drillSelect'];
$date = $_POST['date'];
$inserts = array();
foreach ($drills as $drills)
$inserts[] = "('$id','$drills','','$date')";
$query = "REPLACE INTO exercise_spelare_ref VALUES ". implode(", ", $inserts);
//echo "query = $query"; // for debugging purposes, remove this once it is working
mysql_query($query) or die(mysql_error());
?>
How can I make values that are in the look-up table marked as "checked" in the form?
There are a solution here https://stackoverflow.com/a/4069477 written by Martin Bean but I cant get it to work?
I have been stuck here for ever, hope anyone can help me out here!
I tried Martin Beans script like:
$uid = $row_rsSpelare['id']; // your logged in user's ID
$exercise = array();
// get an array of exercise
$sql = "SELECT drillID FROM exercise";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$exercise[$row->id] = $row->drillID;
}
// get an array of exercise user has checked
$sql = "SELECT DISTINCT drillID FROM exercise_spelare_ref WHERE id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->drillID;
}
// this would be templated in a real world situation
foreach ($exercise as $id => $drillID) {
$checked = "";
// check box if user has selected this exercise
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="drillSelect[]" value="'.$id.'" '.$checked.'/>';
}
But getting a warning:
Warning: in_array() expects parameter 2 to be array, string given in /customers/b/d/e/teeview.se/httpd.www/analys_kund/selectDrills.php on line 158
Line 158 is:
if (in_array($checked, $id)) {
Well, you will need to SELECT the items from the table, store them into an array, and if the current checkbox's ID matches something in the array, add the checked attribute to it in the HTML.

Categories