building an evaluation form php - php

I'm trying to create an evaluation form for students, all questions are stored in db. I'm retrieving them from db any trying to store the answers for each question on db again. all answers should be selected from radio buttons as the following:
<?php
$sql = "SELECT Q_body, Q_ID FROM s_evaluation_questions WHERE Ev_ID='1'";
$result = $conn->query($sql);
?>
<?php
if ($result->num_rows > 0)
{
?>
<form action="AnswerS.php" method="POST">
<table align="right" id="keywords" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th colspan="4"> </th>
<th>Question</th>
</tr>
</thead>
<tbody>
<?php
while($row = $result->fetch_assoc())
{ $answer="s".$row["Q_ID"];
?>
<tr>
<td>
<input type="hidden" name="Q_ID" value="<?php echo $row["Q_ID"]; ?>" >
<input type="radio" name=<?php echo $answer?> value="Bad" >Bad
<input type="radio" name=<?php echo $answer?> value="Good"> Good
<input type="radio" name=<?php echo $answer?> value="VeryGood"> Very Good
<input type="radio" name=<?php echo $answer?> value="Excellent"> Excellent</td>
<td align="right"> <?php echo $row["Q_body"]?></td>
</tr>
<?php } ?>
</tbody>
</table></br></br></br></br></br></br></br>
<input type="submit" value="Send" />
</form>
<?php
?></div>
<?php
} else
{echo "not allowed";}
And on the AnswerS.php page I suppose to store the answers on db as the following:
$UID='1';
$answer=$_POST['answer'];
$Q_ID= $_POST['Q_ID'];
$sql = "INSERT INTO s_evaluation_answers(Q_ID, A_body, UID) VALUES($Q_ID, $answer, $UID) ";
$result = $conn->query($sql);
if ($result === TRUE) {
echo "done" ;
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
but unfortunately it doesn't work!, I tried to trace the value of Q_ID and it gives only the last question id not all questions.
how can I store the selected value from the radio button for each question and store it as the answer for this question? (note: all questions are brought from db)
thanks

If you see your source html you will find that you have many fields with name Q_ID:
<input type="hidden" name="Q_ID" value="one id" >
<input type="hidden" name="Q_ID" value="another id" >
<input type="hidden" name="Q_ID" value="some more id" >
So browser sends you the last value of Q_ID - in above case it is some more id.
To avoid this - use [] notation in name attribute:
<input type="hidden" name="Q_ID[]" value="one id" >
<input type="hidden" name="Q_ID[]" value="another id" >
<input type="hidden" name="Q_ID[]" value="some more id" >
After that, outputting $_POST['Q_ID'] will give you an array. You can iterate over it with foreach and gather other info you need. Something like (simplified):
foreach ($_POST['Q_ID'] as $q) {
// answer will be stored in a `s . $q` value of POST
$answer = $_POST['s' . $q];
$sql = "INSERT INTO s_evaluation_answers(Q_ID, A_body, UID) VALUES($q, $answer, $UID) ";
$result = $conn->query($sql);
}

Related

How to add a delete button in the html table to delete entire row from database? [duplicate]

I have outputted the results of a MySQL table to an HTML table. In the last column, I want to add a delete option which calls another form and deletes the user from the MySQL table. I can't seem to get it to work though.
This is my code for the results page:
<?php
$contacts = mysql_query("
SELECT * FROM contacts ORDER BY ID ASC") or die( mysql_error() );
// If results
if( mysql_num_rows( $contacts ) > 0 )
?>
<table id="contact-list">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>Address</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php while( $contact = mysql_fetch_array( $contacts ) ) : ?>
<tr>
<td class="contact-name"><?php echo $contact['name']; ?></td>
<td class="contact-email"><?php echo $contact['email']; ?></td>
<td class="contact-telephone"><?php echo $contact['telephone']; ?></td>
<td class="contact-address"><?php echo $contact['address']; ?></td>
<td class="contact-delete"><form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
and, this is my delete.php script
<?php
//Define the query
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
//sends the query to delete the entry
mysql_query ($query);
if (mysql_affected_rows() == 1) {
//if it updated
?>
<strong>Contact Has Been Deleted</strong><br /><br />
<?php
} else {
//if it failed
?>
<strong>Deletion Failed</strong><br /><br />
<?php
}
?>
I cannot figure out why this is not working.
You have to pass a variable in the delete link. You have to pass <?php echo $contact['name']; ?> (the name value) in a hidden field or pass this value in URL:
Replace
<td class="contact-delete">
<form action='delete.php' method="post">
<input type="hidden" name="name" value="">
<input type="submit" name="submit" value="Delete">
</form>
</td>
With
<td class="contact-delete">
<form action='delete.php?name="<?php echo $contact['name']; ?>"' method="post">
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
<input type="submit" name="submit" value="Delete">
</form>
</td>
USe javascript
<input name="Submit2" type="button" class="button" onclick="javascript:location.href='delete.php?id=<?php echo $your_id;?>';" value="« Back" />
and in delet.php
$id=$_GET['id'];
and put $id in your sql statement.
You are missing to pass name in this line:
<input type="hidden" name="name" value="">
You need to have something (<?php echo $contact['name']; ?>) in the value attribute.
BTW, do not use deprecated mysql_* functions, use PDO or mysqli_* instead.
<input type="hidden" name="name" value="">
You are missing a value which wil be picked up by this line in your delete file.
$query = "DELETE FROM contacts WHERE name={$_POST['name']} LIMIT 1";
Right now it isn't receiving anything, which is why it will not work.
So add a value to it and it will work. Example:
<input type="hidden" name="name" value="<?php echo $contact['name']; ?>">
First, you should not write the code in that way; the code has no protection against SQL injection.
1. Try to use primary IDs instead of using a name (what happens if 2 people has the same name?).
So, you can create a hidden field to know which 'person' you are dealing with.
<input type="hidden" name="contact_id" value="<?php $contact['contact_id']; ?>">
2. Sanitize variables to avoid attacks:
<?php $contact_id = isset($_POST['contact_id'])?intval($_POST['contact_id']):0;
// proceed with the query
if($contact_id>0) { $query = "DELETE FROM contacts WHERE contact_id = '$contact_id'";
}
// redirect to the main table with header("location: main.php");
?>

How to display certain row's data in a form after clicking edit? (PHP)

enter image description hereI'm new to PHP so please don't judge :D
I'm trying to make table with edit option. No matter in which row I click "Edit" button, only data from last row of the page gets loaded. What should I do?
$sql = "SELECT * FROM countries LIMIT " . $this_page_first_result . ',' . $results_per_page;
$result = $connection-> query($sql);
echo '<div style="text-align:center; font-weight: bold;">';
for ($page=1; $page<=$num_of_pages; $page++){
echo '' . $page . ' ';
}
echo '<div><br>';
if($result-> num_rows > 0){
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$Name = $row['Name'];
$Area = $row['Area'];
$Population = $row["Population"];
$Phone_code = $row["Phone_code"];
echo "<tr><td><a href='cities.php?id={$row['id']}'>".$row['Name']."</a></td><td>". $row["Area"] ."</td><td>"
. $row["Population"] ."</td><td>". $row["Phone_code"] ."</td><td><button id='update-button' onclick='openEdit()'>Update</button></td><td><button id='delete-button'>Delete</button></td></tr>";
}
print_r($row);
}
else{
echo "</table><h2 style='text-align:center'>There are no countries in the database..</h2>";
}
$connection-> close();
?>
</table>
<br>
<div style="text-align:center">
<button type="button" id="close-button-edit" onclick="closeEdit()" style="display:none">Close</button>
<div id="edit_form" style="display:none; text-align:left">
<form action="edit_country.php" method="POST" class="forms">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<p>Name: <input type="text" name="name" required value="<?php echo $Name; ?>"></p>
<p>Area: <input type="text" name="area" required value="<?php echo $Area; ?>"></p>
<p>Population: <input type="text" name="population" required value="<?php echo $Population; ?>"></p>
<p>Phone code: <input type="text" name="phone_code" required value="<?php echo $Phone_code; ?>"></p>
<input type="submit" name="update" value="Update">
</form>
</div>
There are two strategies that can be used for this problem: all php or using JavaScript.
PHP Only
This requires a submission to pre-fill the edit form. Each update button sends the id as a GET request (it is requesting information, not changing information, so use GET), in the form of an ordinary link, which the php script uses to populate the edit form.
<?php
// always start with php stuff and don't issue any html until you're done
// initialization
$sortDirection = 'asc';
if(isset($_REQUEST['sortDirection'])) {
// this decouples the value from user input. It can only be 'Asc' or 'Desc'
$sortDirection = $_REQUEST['sortDirection'] == 'asc' ? 'Asc' : 'desc';
}
$rowToEdit = '';
$pdo = new PDO( ... );
// Using PDO because it is more standard
// Leaving connection details to user. See https://phpdelusions.net/pdo_examples/connect_to_mysql for tutorial
// $pdo is assumed to be the pdo object
// deal with row delete. Destructive, so will be post, and delete button will be set
if(isset ($_POST['delete']) ) {
// delete from countries where id = ?
//redirect back to self (Post, Redirect, Get pattern).
// Always do this when done working with POST submissions!
header('Location: /countries.php');
exit;
}
// deal with row update. This changes data, so use POST
if(isset($_POST['id'])) {
// update countries set ...
// redirect back to self
header('Location: /countries.php');
exit;
}
// deal with request for row to edit, use GET for info requests
if(array_key_exists('id', $_GET) {
$rowToEdit = $pdo->prepare("select * from countries where id = ?");
$rowToEdit->execute([$id]);
// fall through to show page
}
// get all country rows (Note, OK to use $sortDirection here because it is decoupled from user input)
$country = $pdo->query("SELECT * FROM countries ORDER BY NAME $sortDirection")->fetchAll(PDO::FETCH_GROUP);
// got all our data, dealt with user input, now we can present the view
?>
<html>
<head>
</head>
<body>
<h1>Countries</h1>
Sort Asc
Sort Desc
<table>
<tr>
<th>Name</th>
<th>Area</th>
<th>Population</th>
<th>Phone</th>
<th></th>
<th></th>
</tr>
<?php foreach( $country as $row): ?>
<tr>
<td><a href='cities.php?country_id=<?=$row['id']?>'><?=$row['Name']?></a></td>
<td><?=$row["Area"]?></td>
<td><?=$row["Population"]?></td>
<td><?=$row["Phone_code"]?></td>
<td> <a href='countries.php?id=<?=$row['id']?>'>Update</a> </td>
<td>
<form method="post">
<input type="hidden" name="id" value="<?=$row['id']?>" />
<button id='delete-button'>Delete</button>
</form>
</td>
</tr>
</table>
<?php if($rowToEdit): ?>
<div style="text-align:center">
<form action="countries.php" method="POST" class="forms">
<input type="hidden" name="id" value="<?= rowToEdit ['id']?>">
<input type="hidden" name="sortDirection" value="<?= $sortDirection?>">
<p>Name: <input type="text" name="name" required value="<?= $rowToEdit['Name']?>"></p>
<p>Area: <input type="text" name="area" required value="<?= $rowToEdit['Area']?>"></p>
<p>Population: <input type="text" name="population" required value="<?= $rowToEdit["Population"]?>"></p>
<p>Phone code: <input type="text" name="phone_code" required value="<?= $rowToEdit["Phone_code"]?>"></p>
<input type="submit" name="update" value="Update">
</form>
</div>
<?php endif; ?>
</body>
</html>

How to get values from unchecked checkbox [duplicate]

This question already has answers here:
Posting both checked and unchecked checkboxes
(3 answers)
Closed 1 year ago.
I am working on an attendance reporting page. Here I am creating a dynamic checkbox with content from db.
I can store the checked student(present) students detail, but I also want to store the absent student. In order to do that I want a hidden field or something to get the unchecked student details please anyone help me to do that.
<form name="myform" action="" method="post">
<div class="checkbox">
<table border="1" cellspacing="2" cellpadding="5" summary="">
<?php while ($row = mysql_fetch_assoc($res)){?>
<tr>
<td>
<input type="checkbox" class="input" id="input<?php echo $row['st_id']; ?>" name="student[]" value="<?php echo $row['st_id']; ?>" checked="checked">
<?php echo $row['st_name'] ; ?>
<label for="input<?php echo $row['st_id']; ?>"></label>
<input type="text" name="absent" value="0"/>
</td>
</tr>
<?php }?>
</table>
<input type="submit" name="submit" value="submit"/>
</div>
PHP code
<?php
$res = mysql_query("SELECT * FROM `student_info` WHERE `sem`='$selsem'");
if(isset($_POST["submit"]))
{
//Here goes array
for($i=0;$i<count($_POST['student']);$i++)
{
$id=$_POST['student'][$i];
echo $id;
$check=1;
mysql_query("insert into manage_attendance(st_id,date,sem,period,subject,status) values('$id','$seldate','$selsem','$selperiod','$selsub','$check')");
}
}
?>
As #EhsanT said i have solved the problem with sql command...Thankyou EhsanT....
if(isset($_POST["submit"]))
{
$ans=array();
$ans=$_POST['student'];
$re=mysql_query("SELECT `st_id` FROM `student_info`
WHERE `sem` ='$selsem'
AND `st_id` NOT IN (".implode(',',array_map('intval',$ans)).")");
while ($ro = mysql_fetch_row($re)){
mysql_query("insert into manage_attendance(st_id,date,sem,period,subject,status) values('$ro[0]','$seldate','$selsem','$selperiod','$selsub','0')"); }
//Here goes array
for($i=0;$i<count($_POST['student']);$i++)
{
$id=$_POST['student'][$i];
//echo $id;
$check=1;
mysql_query("insert into manage_attendance(st_id,date,sem,period,subject,status) values('$id','$seldate','$selsem','$selperiod','$selsub','$check')");
//print_r ($_POST['student']);
}
}

assign data from one table to a specific table (group)

I have a classrooms in schools and when I click on a certain classroom, I want to add students into it but my actual code is doing something stupid. It adds a student but i can see the student in all classrooms, not just in the one that i added him into. So when Im in classroom number 1, I see a form in there, I can add a student there, ... see how it works here:
here is the code: http://www.xxxx.xx/projekt/
here is my code in file trieda.php
<table align="center"><tr><td>
<form action="vlozit2.php" method="post">
Meno: <input type="text" name="meno" placeholder="Janko" maxlength="15" required>
Priezvisko: <input type="text" name="priezvisko" placeholder="Hruška" maxlength="20" required>
<input type="hidden" name="id_triedy" value="<?= $trieda['id_triedy'] ?>" />
<input type="submit" name="submit" value="Pridať študenta do triedy">
</form>
</td></tr></table>
<?php
$result = mysqli_query($prip,"SELECT * FROM student ORDER BY meno");
while($student = mysqli_fetch_array($result))
{
echo "<br /><table cellspacing='1' cellpadding='1' class='tabulka1' align='center'><tr>";
echo "<td width='200'><a href='student.php?id_triedy=".$trieda['id_triedy']."".id_student=".$student['id_student']."'>".$student['meno']." ".$student['priezvisko']."</a></td>";
?>
<td width='300px' align='right' bgcolor="#fbfbfb">Zmazať</td>
</tr></table>
<?php
}
?>
here is vlozit2.php (a code that works for the form to add a student)
if(isset($_POST['submit']))
{
//meno a priezvisko
$student = $_POST['meno'];
$student = $_POST['priezvisko'];
$trieda = $_POST['id_triedy'];
//connect to the database
include 'config.php';
//insert results from the form input
$sql = "INSERT INTO student (meno, priezvisko, id_triedy) VALUES('$_POST[meno]', '$_POST[priezvisko]', '$_POST[id_triedy]')";
$add = "<table align='center'>
<tr>
<td> Študent bol úspešne pridaný do triedy. </td>
</tr>
<tr>
<td><a href='./trieda.php'><strong>Späť</strong></a></td>
</tr>
</table>";
$not_add = "<table align='center'>
<tr>
<td> Študent s týmto menom a priezviskom už je v tejto triede. </td>
</tr>
<tr>
<td><a href='./trieda.php'><strong>Späť</strong></a></td>
</tr>
</table>";
if (mysqli_query($prip, $sql)) {
echo $add;
}else{
echo $not_add;
}
mysqli_close($prip);
}
?>
Try to replace your part of code with these snipets:
1) in trieda.php
<form action="vlozit2.php?id_triedy=<?php echo $_GET["id_triedy"];?>" method="post">
Meno: <input type="text" name="meno" placeholder="Janko" maxlength="15" required>
Priezvisko: <input type="text" name="priezvisko" placeholder="Hruška" maxlength="20" required>
<input type="submit" name="submit" value="Pridať študenta do triedy">
</form>
2) in vlozit2.php
$student = $_POST['meno'];
$priezvisko = $_POST['priezvisko'];
$id_trieda = $_GET['id_triedy'];
and
$sql = "INSERT INTO student (meno, priezvisko, id_triedy) VALUES( '{$student}', '{$priezvisko}', {$id_trieda} )";
Hopefully you store your id_trieda as INT type.
In your vlozit2.php file is nothing about inserting of class id. So put
<input type="hidden" name="classId" value="<?= $trieda['id'] ?>" />
to your form and in vlozit2.php get this value from $_POST['classId'] and insert it with other students data or anywhere you want to have it.

How to send multiple row value submit button?

I get the values from same row, but many values with fetch array. I did it, but with buttons, as many as how many values there are. If I have 5 rows, then I should have five submits, but I want one submit button.
Here is my code:
$result2 = mysql_query ("select * from price where dom='$cat'",$db);
$myrow2= mysql_fetch_array($result2);
<form action="priceupdatetes.php" method="post">
<?php
do {
echo <<<here
<td><input name="etiket[$myrow2[id]]" type="text" value="$myrow2[etiket]"/></td>
<td><input name="pricestandart[$myrow2[id]]" type="text" value="$myrow2[pricestandart]"/></td>
<td><input name="number[$myrow2[id]]" type="text" value="$myrow2[number]"/></td>
<td><input name="totalunper[$myrow2[id]]" type="text" value="$myrow2[totalunper]" disabled="disabled"/></td>
<td><input name="discount[$myrow2[id]]" type="text" value="$myrow2[discount]"/></td>
<td><input name="totalwithper[$myrow2[id]]" type="text" value="$myrow2[totalwithper]" disabled="disabled"/></td>
</tr>
here;
}
while($myrow2= mysql_fetch_array($result2)) ;
?>
<input NAME="id[]" TYPE=hidden value="<?php foreach($myrow2[id] as $mid) {print $mid;} ?> "/>
<input name="submit" type="submit" value="Submit"/><br>
</form>
HERE is UPDATEPAGE.php:
if (isset($_POST['etiket'])) {$etiket = $_POST['etiket']; }
if (isset($_POST['pricestandart'])) {$pricestandart = $_POST['pricestandart'];}
if (isset($_POST['number'])) {$number = $_POST['number']; }
if (isset($_POST['discount'])) {$discount = $_POST['discount']; }
if (isset($_POST['id'])) {$id = $_POST['id']; }
$totalunper=$pricestandart*$number;
$percent=$discount/100;
$totalwithper1=$totalunper*$percent;
$totalwithper=$totalunper-$totalwithper1;
foreach($id as $team_id)
{
$result = mysql_query("UPDATE price SET etiket='$etiket[$team_id]',pricestandart='$pricestandart[$team_id]',number='$number[$team_id]',totalunper='$totalunper[$team_id]',discount='$discount[$team_id]',totalwithper='$totalwithper[$team_id]' WHERE id='$team_id'"); }
How can I get values with different id's and update them?
<input NAME="id[]" TYPE=hidden value="<?php foreach($myrow2[id] as $mid) {print $mid;} ?> "/>
is wrong. $myrow2[id] is not an array. Inside your while-loop, you should add:
<input NAME="id[]" TYPE="hidden" value="$myrow2[id]"/>

Categories