Submit data in a textbox from a while loop to database - php

I need to enter scores for all subjects offered by all students in a class simultaneously. So I retrieved the students ID, retrieved the list of subjects being offered by the students, and placed a textbox under each subject.
Now, I want to submit the score in the database as well as the subject name and the student ID, but the score is not storing, just the subject name and the student ID.
Here is my code:
<form method="post">
<?php
include "includes/dbcon.php";
$subject_name ="";
echo "<table border='1'><thead><tr><td>Students Name</td>";
$query_subjects = mysqli_query($link,"SELECT * FROM junior_subjects ORDER BY subject_name ASC");
while ($row_subject=mysqli_fetch_array($query_subjects))
{
$subject_name .= $row_subject['subject_name'];
echo "<td>".$row_subject['subject_name']."</td>";
}
echo "</tr></thead>";
$query_students = mysqli_query($link,"SELECT * FROM students WHERE class_cat='Junior'");
while ($row_students=mysqli_fetch_array($query_students))
{
$student_id = $row_students['student_id'];
echo "<tr><td>".$row_students['student_id']."</td>";
$query_subjects2 = mysqli_query($link,"SELECT * FROM junior_subjects ORDER BY subject_name ASC");
while ($row_subject2 =mysqli_fetch_array($query_subjects2))
{
$subject_name2 =$row_subject2['subject_name'];
echo "<td>
<input type='text' hidden name='$subject_name2'>
<input type='text' size='4' name='$subject_name2'>
</td>";
/////
if (isset($_POST['submit']))
{
$score = $_POST[$subject_name2];
mysqli_query($link,"INSERT INTO score_sheet(student_id,subject_name,score) VALUES('$student_id','$subject_name2','$score') ");
}
}
}
?>
<input type='submit' name='submit'>
</form>

You should have the input score as array and make a foreach loop to insert the query.
You should have the input field like this
And do a foreach loop like this
$score = $_POST['score'];
foreach ($score as $key)
{
$query = "INSERT INTO score_sheet(student_id,subject_name,score) VALUES('$student_id','$subject_name2','$key') ";
$query = mysqli_query($link,$query);
}
Note :
You should not have have two forms inside it.
I have made an eval for you
Warning :
It is not at all a good practise to have such a bulk entry.

Related

How to compare two SQL database table and mark checkbox based on result using php

Hope you are doing great. So I am working on a automated attendance system using face recognition and I am displaying data through php.
I have a SQL database with the name of student_db and there are two tables in it with the name of mark_attendance and student_detail. Face recognition system recgnize faces and send rollnumber and date on mark_attendance
enter image description here
where as student_detail consist of whole class students name and rollnumber.enter image description here enter image description here
I am displaying name, rollnumber and a checkbox on frontend what I want to do is to mark checkbox aUtomatically if student is present. It should compare data of mark_attendance table with the studet_detail table and mark checkbox.
I AM ATTACHING THE CODE I HAVE TRIED BUT ITS NOT WORKING.
<html>
<head></head>
<body>
<table border="1">
<tr>
<th> Name </th>
<th> Attendance </th>
</tr>
<?PHP
include('db_connection.php');
$qry = "SELECT * FROM student_detail";
$result = mysqli_query($db_con, $qry);
$ftch = mysqli_fetch_assoc($result);
$markattendance = "SELECT * FROM mark_attendance ";
$ma = mysqli_query($db_con, $markattendance);
if(mysqli_num_rows($result) > 0)
{
foreach($result as $r)
{
$sav = "SELECT * FROM mark_attendance t1
JOIN student_detail t2
ON t2.rollno = t1.rollno";
$sa = mysqli_query($db_con, $sav);
$s = mysqli_fetch_assoc($sa);
$count = mysqli_num_rows($sa); echo "</b>";
echo "<table><tr>";
echo "<td>".$r['Name']."</td>";
// echo $r['rollno'];
echo $s['rollno'];
if($count >= 1 && $s['rollno'] == $r['rollno']){
echo "<form><td> <input type='checkbox' checked value=".$r['Name']."></td>";
}
else{
echo "<form><td> <input type='checkbox' value=".$r['Name']."></td>";
}
// echo "<form><td> <input type='checkbox' value=".$r['Name']."></td>";
// echo "<td> <input type='text' value=".$r['rollno']."></td></form>";
echo "</tr>";
}
}
?>
</table>
</body>
</html>
Its MARKING only the first data checkbox on db not other after it.
I also have tried with while loop and other stuff but its still not working can you run it on your computer and provide me the working code.
SORRY FOR THE BAD ENGLISH

$_POST Insert into many to many, wrong PHP Syntax?

EDIT: IGNORE ANY SQL INJECTIONS OR VULNERABLE CODE STATEMENTS :D
(School Project).
I wish to create a insert form on my webpage where I can select an artist from a table, including a song from a table and combine them for an insert into a combined foreign key table.
I have managed to do selects and insert with only individual artist and song drop-downs on my web-page, but would wish for combining the two ID's from each table to combine them to a many to many relative table. But when I press the submit button nothing happens, and I'm a beginner and don't know if I'm missing any important bits of actually Posting the information.
For troubleshooting I have tried my code, and tested it. I see if I remove my code theres no problem, so the problem persists on the syntax I believe, as the first dropdown shows, alongside the second dropdown and submit button, but the problem is within the actual processing and SQL query part, where it never goes to the DB..
The problem:
As you can see below I have a the text Song Name appear with a drop-down menu in the bottom left corner including the Artist Name with a submit button. But my problem persists as the select and then insert from the two drop downs into the combined table does not work, it does not actually submit, I want it to post into the DB what can I do. But somethings off? I would appreciate any questions or help, this community is so amazing and wonderful to operate in!
Database
PHP
<form method='POST'>
<?php
include('connect_mysql.php');
if(isset($_POST["mangetilmange"])) {
$song_id = $_POST["song_id"];
$artist_id = $_POST["artist_id"];
$sql ="INSERT INTO artist_has_song (song_id, artist_id) VALUES
('$song_id', '$artist_id')";
if($conn->query($sql)) {
echo "Completed";
} else {
echo "Blablalbablablablablablablabl $sql
($conn->error.";
}
}
?>
Song Name
<?php
$sql = "SELECT * FROM song";
$resultat = $conn->query($sql);
echo "<select name='song_id'>";
while ($rad = $resultat->fetch_assoc()) {
$song_id = $rad["song_id"];
$songname = $rad["songname"];
echo "<option value='$song_id'>$songname</option>";
}
echo "</select>";
?>
Artist Name
<?php
$sql = "SELECT * FROM artist";
$resultat = $conn->query($sql);
echo "<select name='artist_id'>";
while ($rad = $resultat->fetch_assoc()) {
$artist_id = $rad["artist_id"];
$artistname = $rad["artistname"];
echo "<option value='$artist_id'>$artistname</option>";
}
echo "</select>";
?>
</form>
<input type="submit" name="mangetilmange" value ="Submit">
change you code to this:
<form method='POST'>
<?php
include('connect_mysql.php');
if(isset($_POST["mangetilmange"])) {
$song_id = $_POST["song_id"];
$artist_id = $_POST["artist_id"];
$sql ="INSERT INTO artist_has_song (song_id, artist_id) VALUES
('$song_id', '$artist_id')";
if($conn->query($sql)) {
echo "Completed";
} else {
echo "Blablalbablablablablablablabl";
}
}
?>
Song Name
<?php
$sql = "SELECT * FROM song";
$resultat = $conn->query($sql);
echo "<select name='song_id'>";
while ($rad = $resultat->fetch_assoc()) {
$song_id = $rad["song_id"];
$songname = $rad["songname"];
echo "<option value='$song_id'>$songname</option>";
}
echo "</select>";
?>
Artist Name
<?php
$sql = "SELECT * FROM artist";
$resultat = $conn->query($sql);
echo "<select name='artist_id'>";
while ($rad = $resultat->fetch_assoc()) {
$artist_id = $rad["artist_id"];
$artistname = $rad["artistname"];
echo "<option value='$artist_id'>$artistname</option>";
}
echo "</select>";
?>
<input type="submit" name="mangetilmange" value ="Submit">
</form>

When form submitted then all rows take one value

I am newbie in PHP and with this less knowledge of PHP i developed a form to update the rows of MySQL table. But the problem is that if i edit one row in index.php file and submit it then that row value comes to all rows of the table.
I want to change the edited inputs and the rest inputs should be unchanged.
Please note that first row budget value will be added when second row budget value and will be inserted in total input and will save to database
This is how it looks
this is the index.php file
<?php
$con=mysqli_connect("127.0.0.1","root","","ji001");
$result = mysqli_query($con,"SELECT * FROM finance")
or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result))
{ $Budget = $row['Budget'];
$Availed_in_Regions = $row['Availed_in_Regions'];
echo "<form style='width:780px' action='update2.php' method='post' class='form-group'>
id<input type='text' name='Budget' value='".$row['ID']."'>
Budget<input type='text' name='Budget' value='".$row['Budget']."'>
Availed in Regions <input type='text' name='Availed_in_Regions' value='".$row['Availed_in_Regions']."'>
<input type='Submit'>
</form>";
}
?>
This is the update2.php file
<?php
mysql_connect('127.0.0.1', 'root', '') or die(mysql_error());
mysql_select_db("ji001") or die(mysql_error());
$ud_Budget = mysql_real_escape_string($_POST["Budget"]);
$ud_Availed_in_Regions = mysql_real_escape_string($_POST["Availed_in_Regions"]);
$query="UPDATE finance SET Budget = '$ud_Budget', Availed_in_Regions = '$ud_Availed_in_Regions'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>Record Updated<p>";
}else{
echo "<p>Not Updated<p>";
}
?>
Firstly, your form having typo id and name having same name for the name attribute i.e. name='Budget'
index.php
echo "<form style='width:780px' action='update2.php' method='post' class='form-group'>";
while($row = mysqli_fetch_array($result))
{
$Budget = $row['Budget'];
$Availed_in_Regions = $row['Availed_in_Regions'];
echo "id<input type='text' name='id[]' value='".$row['ID']."'>
Budget<input type='text' name='Budget[]' value='".$row['Budget']."'>
Availed in Regions <input type='text' name='Availed_in_Regions[]' value='".$row['Availed_in_Regions']."'>";
}
echo "<input type='Submit' value='Submit'></form>";
and you need to change your update query from
update2.php
$ud_id = $_POST["id"];
$ud_Budget = array_map('mysql_real_escape_string', $_POST['Budget']);
$ud_Availed_in_Regions = array_map('mysql_real_escape_string',$_POST["Availed_in_Regions"]);
foreach($ud_id as $key => $value){
$query = "UPDATE finance SET Budget = '$ud_Budget[$key]', Availed_in_Regions = '$ud_Availed_in_Regions[$key]' where ID = $value";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>Record Updated<p>";
}else{
echo "<p>Not Updated<p>";
}
}
Here I have added where condition which is required to identify which row you need to update and
NOTICE : You were mixing two API within index.php you were using mysqli_ and within update2.php its mysql
You are not using a where clause in the $query query.
it should be something like this
$query="UPDATE finance SET Budget = '$ud_Budget', Availed_in_Regions = '$ud_Availed_in_Regions' WHERE id = '$id'";
You should also pass this id in the form, also change the name of the input field containing the id...
Because you actually SELECT every row in your table.
UPDATE finance SET Budget = '$ud_Budget', Availed_in_Regions = '$ud_Availed_in_Regions';
There is no WHERE clause (link) in your query you have to use it if you wanna update a row in your table.
Pass $id to your update2.php and use this query instead:
UPDATE finance SET Budget = '$ud_Budget', Availed_in_Regions = '$ud_Availed_in_Regions' WHERE id = '$id';

mysqli join two tables to match user name with the corresponding user id

I'm having a hard time figuring this out..
I have two tables "teacher_info" and "section_info".
In my forms I included all the attributes in my section_info table except I used teacher name instead of teacher id for easy selection which is a dropdownlist of teacher's name, this is my code
<?php
include("anhsis.php");
mysqli_select_db($con,"anhsis");
$result= mysqli_query($con,"SELECT t_lname,t_fname FROM teacher_info");
echo"<select name='adviser' class='form-control' required>";
echo"<option value='0'>--Select Adviser--</option>";
while ($row=mysqli_fetch_array($result)) {
echo "<option value='".$row['t_lname']."".$row['t_fname']."'>".$row['t_lname'].", ".$row['t_fname']."</option>";
}
echo'</select>'
?>
and heres my php code to insert data in "section_info"
<?php
include_once('anhsis.php');
$room_id = $_POST['room_id'];
$section = $_POST['section'];
$adviser = $_POST['teacher_id'];
$level = $_POST['level'];
$curriculum = $_POST['curriculum'];
mysqli_select_db($con,"anhsis");
$result= mysqli_query($con,"SELECT * FROM section_info WHERE room_id= '$room_id'");
if (mysqli_num_rows($result)>0){
echo '<script type="text/javascript">';
echo 'alert("TIN No already exist!")';
echo '</script>';
}
else{
mysqli_query($con,"INSERT INTO section_info VALUES('$room_id','$section','$adviser','$level','$curriculum')");
}
?>
my problem is that in my section_info theres no attribute of teacher's name, instead it has teacher_id. So how am I going to insert teacher_id from the "teacher_info" table to the "section_info" table by just selecting the teacher's name in my dropdownlist. Or is it possible?
Thanks!
$result= mysqli_query($con,"SELECT t_lname,t_fname,teacher_id FROM teacher_info");
echo "<select name='adviser' class='form-control' required>";
echo "<option value='0'>--Select Adviser--</option>";
while ($row=mysqli_fetch_array($result)) {
echo "<option value='".$row['teacher_id']."'>".$row['t_lname'].", ".$row['t_fname']."</option>";
}
This way you will have teacher_id value in $adviser variable, ready to use.

php can't delete more than one row

I'm using a form with several checkboxes to make the user to select which rows he want to delete. The code to generate the form is this:
if ($busqueda!=""){
$busca = mysqli_query($con, " SELECT id_user FROM usuarios WHERE
id_user LIKE '%$busqueda%'");
echo "<form action='borrar.php' method='post' enctype='multipart/form-data'>";
while ($array= mysqli_fetch_array($busca)){
$user=makestring($array);
echo"Usuario: <input type='checkbox' name='borrar_usuario' value='$user' />$user<br/>";
}
echo " <input type='submit' name='boton' value='eliminar' />";
echo "</form>";
The code in borrar.php to delete the rows is this:
if(isset($_REQUEST["borrar_usuario"])) {
foreach ($_POST as $valor){
$del_user = $valor;
$q_borrar = "delete from usuarios where id_user in ('$del_user')";
mysqli_query($con, $q_borrar)or die(mysqli_error());
}
//echo "usuario borrado";
header('refresh: 3; url= exito.php');
}
The problem is that only deletes the first row selected and I do not know how to make it to delete all the options selected in the form. Any help, please?
First change the name of your checkbox to include []. Then when you submit the form php will convert it to an array.
<input type='checkbox' name='borrar_usuario[]' value='$user' />
Then in the php code that handles the form submission remove the loop and have this
if(isset($_REQUEST["borrar_usuario"])) {
$q_borrar = "delete from usuarios where id_user in ('" . implode("','", $_POST['borrar_usuario']) . "')";
mysqli_query($con, $q_borrar)or die(mysqli_error());
//echo "usuario borrado";
header('refresh: 3; url= exito.php');
}
I think this will work :
if(isset($_POST['borrar_usuario']))
{
$q_borrar = "delete from usuarios where id_user in ($_POST['borrar_usuario'])";
mysqli_query($con, $q_borrar) or die(mysqli_error());
}

Categories