I have done a form which retrieves data from the database. This form allows you to display the list of students from the database but the problem is I cannot correctly input their scores individually. It does allow to insert scores but unfortunately, it only accepts the last score from the last student and inputs the same score to all students.
These are my codes:
FORM code
if ($result->num_rows > 0) { // output data of each row
while($row = $result->fetch_assoc()) {
if($row['status']=='p'){
<form name="result" method="post">
<?php { //this form will display the set of students
echo $row['lastname'] . ', ' . $row['firstname'];
echo '<input type="hidden" name="selected[]" value="'.$row['reviewee_idnumber'].'"/>'; ?>
<input type="text" name="score" required="required" size="20" placeholder="Score"/><br><br>
<?php echo '</br>';
}
} //if statement
} //while statement
?>
<input type="submit" name="submit" value="Submit"/>
<input type="hidden" name="code" value="<?php echo $code;?>"/>
<input type="hidden" name="subject" value="<?php echo $subject;?>"/>
<input type="hidden" name="items" value="<?php echo $items;?>"/>
<input type="hidden" name="date" value="<?php echo $date;?>"/>
</form>
This is where I insert my code into the database
if(isset($_POST['submit'])){
$code = $_POST['code'];
$subject = $_POST['subject'];
$items = $_POST['items'];
$date = $_POST['date'];
$score = $_POST['score']; //get score
$update = mysql_query("INSERT INTO exam (exam_code, subject, date, total_item)
VALUE ('$code','$subject', '$date', '$items')");
if(!empty($_POST['selected'])) {
$checked_count = count($_POST['selected']);// Counting number of checked checkboxes.
//echo "You have selected following ".$checked_count." option(s): <br/>";
foreach($_POST['selected'] as $selected){ // Loop to store and display values of individual inputs.
$updatedata="INSERT INTO result (score, exam_code, reviewee_idnumber)
VALUE ('$score', '$code', '$selected')";
if(#mysql_query($updatedata,$dbc)){
print '<p> successful!</p>';
}else{
print '<p> failed. '.mysql_error().'</p>';
}
It should display list students (which is fine) and right beside their name is a blank space that will accept their score (which doesn't work).
Because <form name="result" method="post"> is inside the while loop, you actually have multiple forms in your page. The submit button acts only on the last form, that's why only the last student's score gets updated.
Also, because there are multiple input elements with the same name, only a single value is sent in the POST request. A solution for this would be to include the student's ID in the name:
name="score'.$row['reviewee_idnumber'].'"
You need to update the form processing logic accordingly.
name =<?php echo "'score.$row['reviewee_idnumber']'" ?>
Related
In the form below, students are selected from student table in my DB. For each student selected a checkbox is checked if the student is absent and left unchecked if the student is present. The form is later on submitted for it to be inserted in the exam_status table in my DB.
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="matricule[]" value="<?php echo "$studentmatricule)"; ?>" readonly>
<label>Name</label>
<input type="text" name="name[]" value="<?php echo "{$studentname} {$studentsurname}"; ?>" readonly>
<label > Absent
<input type="checkbox" name="absent[]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
and my action page "action.php" is as follows
$matricule = $_POST['matricule'];
$absent=$_POST['absent'];
for ($i=0; $i<sizeof($matricule); $i++)
{
if($absent[$i]=='absent')
{
$status='absent';
}else{
$status='present';
}
$query = "INSERT INTO exam_status (student_matricule,status) VALUES ('". $matricule[$i] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
Now the issue is it doesn't just work as i want. the result always gives the first student absent and the rest present. I have tried all i can and have really researched too but with no success at all. Please anyone around to help me out?
Thanks in advance!
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
$index = 0;
while($row= $result->fetch_assoc())
{
$index++;
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][matriculate]" value="<?php echo $studentmatricule; ?>" readonly>
<label>Name</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][name]" value="<?php echo $studentname." ".$studentsurname; ?>" readonly>
<label > Absent
<input type="checkbox" name="studenInfo[<?php echo $index; ?>][status]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
Update your mail file like this. I have changed the form names into a single array. The reason is the checkbox values won't post to the page when the values are not checked. So its not possible to track which one was checked and which is not if you have same name.
And update your action.php like this,
<?php
$conn = mysqli_connect("localhost","username","password","db_name"); // update this values as per your configuration
$studenInfo = (!empty($_POST['studenInfo'])) ? $_POST['studenInfo'] : [];
foreach($studenInfo as $value ) {
$status = (isset($value['status'])) ? 'absent' : 'present';
$query = "INSERT INTO exam_status (student_name, student_matricule,status) VALUES ('". $value['name'] . "','". $value['matriculate'] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
?>
I have used my own table schema where i have added student_name in exam_status table for better tracking. Now you can see the values updating correctly. Also we can use bulk insert if we need to insert multiple data (Note : I haved used the bulk insert in this answer, i just followed the way you used)
I have this table in with some rows and values in it, i get those values in my php page and user selects them and submits the same to insert the selected into another page.
So, here the main catch,
I wrote a sql query with 3 input boxes in which one takes input number from user and multiplies it with other default number in input box 2(which get the value from table1) and prints it out in input box 3.
I wrote JS code for it and it works fine. now i added php to it, in a way that input box 1 takes value directly from php table row and multiplies it with user inserted value in box2 and prints it in box 3
It still works fine even with multiple queries, cause i have made the id value of each box dynamic.
But the problem rises as when i try to submit the three input box values, it works fine for one query/when one row in table1 but when there are multiple queries, it only inserts the first query (3 input box values) and skips the rest of the queries.
My Php , Js, Html code goes as:
<?php
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
?>
<input type="number" name="input1" form="checkout" class="input1" id="input1_<?php echo $row2['id']; ?>" value="<?php echo $row2['price']; ?>">
<input type="text" name="input2" class="input2" id="input2_<?php echo $row2['id']; ?>" value="0" >
<input type="text" name="output" class="output" form="checkout" id="output_<?php echo $row2['id']; ?>" value="">
<form method="post" action="submit.php" id="checkout">
<input type="hidden" value="<?php echo $row2["id"]; ?>" name="id"/>
<button type="submit" class="btn btn-primary btn-sm btn-block">
<h4>Submit</h4>
</button>
</form>
The submit page looks like this..
$input1 = $_POST['input1'];
$output = $_POST['output'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table2 (input1, output)
VALUES ('$input1', '$output')";
if ($conn->query($sql) === TRUE) {
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
Now the problem is , it works fine inserting data from input1 and output boxes into tabll2 when there is only one query in table 1,
but when there are multiple queries in table 1, it only inserts the first query leaving the rest untouched with no error.
Any help is appreciated..
Then main reason is that all the text boxes for input1 field have one name, then at the result there is only one variable $_POST["input1"], so for other text boxes.
You must set an array-like names for your text boxes:
<?php
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
?>
<form method="post" action="submit.php" id="checkout">
<?php
while($row2 = $result2->fetch_assoc()) {
?>
<input type="number" name="input1-<?php echo $row2['id']; ?>" form="checkout" class="input1" id="input1_<?php echo $row2['id']; ?>" value="<?php echo $row2['price']; ?>">
<input type="text" name="input2-<?php echo $row2['id']; ?>" class="input2" id="input2_<?php echo $row2['id']; ?>" value="0" >
<input type="text" name="output-<?php echo $row2['id']; ?>" class="output" form="checkout" id="output_<?php echo $row2['id']; ?>" value="">
<?php
}
?>
<input type="hidden" value="<?php echo $row2["id"]; ?>" name="id"/>
<button type="submit" class="btn btn-primary btn-sm btn-block">
<h4>Submit</h4>
</button>
</form>
<?php
}
?>
Then you must set the submit page:
<?php
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT * FROM table1 WHERE value= '$value'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$input1 = $_POST['input1-'.$row2['id']];
$output = $_POST['output-'.$row2['id']];
$sql = "INSERT INTO table2 (input1, output) VALUES ('$input1', '$output')";
if ($conn->query($sql) === TRUE) {
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
}
?>
I want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.
This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />
<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>
Suppose the user checks the first three boxes , and enters the values like in this picture -
when I click add, I get the values --
Physics
Math
Chemistry
by using the code below:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>
but how do I get the values like this-
Physics,40,30
Math,40,30
Chemistry,30,25
I want this output in a variable so that I can store it in my database table.
I have spent several hours behind this in last few days. Please help me with this one.
you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.
Second, you need to write PHP code, that's concatenating those values.
For example, your HTML code might be:
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />
and your PHP code might be:
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
$total = $_POST['total'][$selected];
$pass = $_POST['pass'][$selected];
$var = $selected . ',' . $total . ',' . $pass;
echo $var . '<br />';
}
}
}
I have an administrator.php which displays 300 records from a table called 'player'. Next to each record, there is an edit option which redirects you to edit.php and the 15 columns of that record (including the primary key - playerid) is displayed inside text boxes. Line of code below:
<a href='edit.php?playerid=".$query2['playerid']."'>Edit</a>
On edit.php you are able to change data of these columns. Upon submit, an update query is sent to update the table but unfortunately, it's not working. My error message continues to display ("testing for error..."); not sure why.
//Setups up the database connection
$link = mysql_connect("localhost", "root", "");
mysql_select_db("fantasymock", $link);
if(isset($_GET['playerid'])) {
$playerid = $_GET['playerid'];
//Query to display results in input box
$query1 = mysql_query("SELECT * from player WHERE playerid = '$playerid'");
$query2 = mysql_fetch_array($query1);
}
if(isset($_POST['submit'])) {
$playerid = $_POST['playerid'];
$preranking = $_POST['preranking'];
$playerlast = $_POST['playerlast'];
$playerfirst = $_POST['playerfirst'];
$position = $_POST['position'];
$battingavg = $_POST['battingavg'];
$run = $_POST['run'];
$homerun = $_POST['homerun'];
$rbi = $_POST['rbi'];
$sb = $_POST['sb'];
$win = $_POST['win'];
$save = $_POST['save'];
$strikeout = $_POST['strikeout'];
$era = $_POST['era'];
$whip = $_POST['whip'];
//Query to update dB
$query3 = mysql_query("UPDATE player SET playerid='$playerid', preranking='$preranking', playerlast='$playerlast', playerfirst='$playerfirst', position='$position', battingavg='$battingavg', run='$run', homerun='$homerun', rbi='$rbi', sb='$sb', win='$win', save='$save', strikeout='$strikeout', era='$era', whip='$whip' WHERE playerid='$playerid'");
header("Location: administrator.php");
} else {
echo "Testing For Error....";
}
?>
<form action="" method="POST">
Player ID:<input type="text" name="playerid" value="<?php echo $query2['playerid'];?>"/> <br/>
Preranking:<input type="text" name="preranking" value="<?php echo $query2['preranking'];?>"/> <br/>
Last Name:<input type="text" name="playerlast" value="<?php echo $query2['playerlast'];?>"/> <br/>
First Name:<input type="text" name="playerfirst" value="<?php echo $query2['playerfirst'];?>"/> <br/>
Position:<input type="text" name="position" value="<?php echo $query2['position'];?>"/> <br/>
Batting Avg:<input type="text" name="battingavg" value="<?php echo $query2['battingavg'];?>"/> <br/>
Runs:<input type="text" name="run" value="<?php echo $query2['run'];?>"/> <br/>
Homeruns:<input type="text" name="homerun" value="<?php echo $query2['homerun'];?>"/> <br/>
Rbi:<input type="text" name="rbi" value="<?php echo $query2['rbi'];?>"/> <br/>
Sb:<input type="text" name="sb" value="<?php echo $query2['sb'];?>"/> <br/>
Wins:<input type="text" name="win" value="<?php echo $query2['win'];?>"/> <br/>
Saves:<input type="text" name="save" value="<?php echo $query2['save'];?>"/> <br/>
Strikeouts:<input type="text" name="strikeout" value="<?php echo $query2['strikeout'];?>"/> <br/>
Era:<input type="text" name="era" value="<?php echo $query2['era'];?>"/> <br/>
Whip:<input type="text" name="whip" value="<?php echo $query2['whip'];?>"/> <br/>
<br>
<input type="submit" name="submit" value="submit">
</form>
FYI: Every column in the table and tablename is spelled correctly, I've triple checked before posting. And I'm aware of MySQL injection. Can someone see a problem? Thank you in advance!
EDIT: I just added an additional if statement if($query3) and it now works.
You are checking for POST variables, but you are getting to edit.php through a GET request. There isn't anything on $_POST. Therefore it drops down to the else of your if block and prints out Testing For Error...
Your script in getting into the else part. That means there nothing it is getting as $_POST['submit']. Make sure that your submit button must have a name attribute as submit.
<input type="submit" name="submit" value="" />
please check what showing in error.log file. You may insert these lines at your edit.php file
error_reporting(E_ALL);
ini_set('display_errors', 1);
to display error.
Replace your else part by this for more detailed mysql errors
else{ echo "Testing For Error...." .mysql_error(); }
<form action="" method="post">
<?php
include 'Includes/database_connection.php';
$sql = "select * FROM sims" ;
$result = mysql_query($sql,$con);
while($row = mysql_fetch_assoc($result)){
?>
<ul class="category_list">
<input type="hidden" value="$id1" name="hidden">
<li><?php echo $row['phonenr'];?><input type="hidden" value="<?php echo $row['id'];?>" name="id"></li>
</ul>
<?php
}
?>
<input type="submit" name="submit">
</form>
So i got the above form where you can select phonenumbers and when you submit them a database should be updated. And there are 23 id's in it. After submitting the form it always takes the last value. What am i doing wrong?
if(#$_POST ['submit'])
{
$id = $_POST["id"];
echo $id;
include 'Includes/database_connection.php';
mysql_query("UPDATE pairings SET sim_id='$id'
WHERE unit_id='$id1'")
}
Change your hidden field name to array like this
<input type="hidden" value="<?php echo $row['id'];?>" name="id[]">
then on PHP side use loop to retrieve
foreach ($_POST['id'] as $val) {
$id = $val;
include 'Includes/database_connection.php';
mysql_query("UPDATE pairings SET sim_id='$id'
WHERE unit_id='$id1'")
}
Slight modification specified by chandresh_cool, would get the result that you expect.
The input name is replaced with id, so the post key contains only the row[id], not the $_POST['id']
Instead change the name of the hidden field to accept as a array like this
<input type="hidden" value="<?php echo $row['id'];?>" name="id[]">
Then you can iterate id array as specified by chandresh_cool