Storing values from dropdowns to Database using PHP - php

I am working on an attendance module. Initially, it will show the list of all students along with a dropdown having options Present/Absent. The faculty member will choose Present/Absent accordingly & submit the same.
I am having problem in storing the corresponding values to the DB.
$sql = "select a.student_id, r.student_name, r.section, r.group_name, a.$subject from result.$batch r, attendance.$batch a where a.student_id = r.student_id AND r.section='$section'";
$c = 1;
$result1 = $result->query($sql);
if ($result1->num_rows > 0)
{
while($row = $result1->fetch_assoc())
{
echo '<tr>';
echo "<td>$c </td>";
echo "<td>{$row['student_id']}</td>";
echo "<td>{$row['student_name']}</td>";
echo "<td>{$row['section']}</td>";
echo "<td>{$row['group_name']}</td>";
echo "<td>
<select class='dropdown' id='attend' name='attend[$c]' > <option value='1'>Present</option> <option value='2'>Absent</option>
</td>";
echo '</tr>';
++$c;
}
}
else
{
echo "No Results Found";
}
Can someone please help me with the updation code. Updation is to be made in the table $batch (batch is a variable containing Table Name to use) and column $subject (contains variable name).

well, you can do one thing.when user clicks on the check-box to mark absent or present, save it into an array using Javascript like :
onclick='array.push(this.id);'
this would push the id of current element to an array in Javascript.
When you finally submit the form, just do this,
onsubmit="passValues();"
in script tag, do this
function passValues()
{
var x = array // the array to which elements were pushed
document.getElementById('someBlankElement').innerHTML = "<input type='hidden' value = 'display array here' name='get_this_name_through_php_when_form_submits' >"
}
and done !

Related

How to add multiple checkboxes in PHP and mysql with different user id

I am developing a platform that allows me to enter presences at an event and I am stuck in one place. How can I load a series of checkboxes in order to change the user ID for each item?
A practical example, I have a table containing the name of all the people and next to it a checkbox once pressed submit php must upload the data for each user to the db.
Below the html form and the php script that manages the upload to the db.
'''php
<?php
$query = "SELECT * FROM utenti";
$ris = mysqli_query($conn, $query);
//$dati = mysqli_fetch_array($ris);
while($row = mysqli_fetch_assoc($ris)){
echo "<tr><td>".$row['nome']."</td>";
echo "<td>".$row['cognome']."</td>";
echo "<td>".$row['squadra']."</td>";
echo "<td>
<input type='checkbox' name='presenza' data-toggle='toggle' data-onstyle='success' data-offstyle='danger' data-on='Presente' data-off='Assente' value='1'>
</td></tr>";
}
'''
if (isset($_POST['submit'])){
if(!empty($_POST['presenza'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['presenza'] as $selected){
echo $selected."</br>";
$sql="INSERT INTO presenze(id_utente,settimana,presenza) VALUES ('1','1','$selected')";
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
}
}
}
'''
One of the way to get relationship between a user and a checkbox is to use user ID (or whatever unique identifier you have in your tables structure) in checkbox name e.g.:
"<input type='checkbox' name='presenza_" . $row['user_id'] . "'>"
Then on the backend you can iterate over all post params with presenza_ prefix and get user ID from it.
So your code will be a bit more sophisticated:
foreach($_POST as $param_key) {
// working only with params started with presenza_
if (0 !== strpos($param_key, "presenza_")) {
continue;
}
$presenza_parts = explode("_", $param_key);
$user_id = (int)$presenza_parts[1];
}
Keep in mind that checkbox field sends only value if it's switched on and sends nothing if it's switched off.

insert checkbox value into mysql database

I want to enroll the student and insert the student id into Mysql database after I check and submit the checkbox value, but I already tried so many ways but still cannot...
This is the php code
<?php
if (isset($_POST['submitxd'])) {
foreach ($_POST['enrol'] as $items) {
$insert = $link->query("INSERT INTO student_course(studentID) values ('$items')");}
}
?>
This is the html code
$result = $link->query("SELECT * FROM student WHERE programmeName = '$programme' AND intake = '$intake'");
while ($row = mysqli_fetch_array($result)) {
echo "<tr>
<td>".$row['studentID']."</td>
<td>".$row['studentName']."</td>
<td>".$row['studentGender']."</td>
<td>".$row['studentContact']."</td>
<td>
<input type='checkbox' name='enrol[]' value='".$row['studentID']."'>
</td>
</tr>";
}
check whether your array contains values or not:
echo "<pre>";
print_r($_POST['enrol']);
echo "</pre>";
if not, you should write html code properly i.e. check form tag and its action path carefully and before submitting the form, remember to check out the checkbox

getting data from $_POST and Showing specific data in php

This may have been asked before but i have not been able to find it.
I have created a dropdown list in a form to show a selection from a database.
I am then sending that information via $_POST to another page.
But i am only getting the one result (eg plantID).
$sql = "SELECT DISTINCT * FROM PLANTS";
$result = mysqli_query($mysqli,$sql)or die(mysqli_error());
//********************* Botannical name drop down box
echo "<form name='selection' id='selection' action='profile.php' method='post'>";
echo "<select name='flower'>";
while($row = mysqli_fetch_array($result)) {
$plantid = $row['FlowerID'];
$plantname = $row['Botannical_Name'];
$plantcommon = $row['Common_Name'];
$plantheight = $row['Height'];
$plantav = $row['AV'];
$plantcolours = $row['Colours'];
$plantflowering = $row['Flower_Time'];
$plantspecial = $row['Special_Conditions'];
$plantfrost = $row['Frost_Hardy'];
$plantaspect = $row['Aspect'];
$plantspeed = $row['Growth_Speed'];
echo "<option value=".$plantid.">".$plantname." -> AKA -> ".$plantcommon."</option>";
}
echo "</select>";
echo "<br />";
//********************* End of form
echo "<input type='submit' name='submit' value='Submit'/>";
echo "</form>";
Is there any way i can send all the data via post or
can i somehow get the required PlantID from the database and show all the information for that record in a table on the second page.
Hope this makes sense to someone out there :D
Although technically you can, it is not advised nor used anywhere.
Just send an id like you do right now and then select all the data with another query based on this id.

Create a PHP array from an array from of HTML input values in a for loop

I've trying to create an array that consists of the values of inputs in loops. I am very new to PHP and looked up several other questions but to no avail. I am taking a random number "$QuestionNoSelect" and selecting a text and info from a MySQL server about the question.
//For loop for displaying and naming
for($i = 0; $i < 11; $i++)
{
$QuestionNoSelect = rand(1,16);
array_push($IDListing, $QuestionNoSelect);
$sql = "SELECT QuestionText FROM johnconn_sstest.tbRandomArray WHERE QuestionNo = $QuestionNoSelect";
$QuestionText = $conn->query($sql);
if ($QuestionText->num_rows > 0)
{
// output data of each row
while($row = $QuestionText->fetch_assoc())
{
//Number Question, Increment, Question then input box
echo "<br><br>".$QuestionNumberer. ". ". "<br>";
echo "Question number ID= ".$QuestionNoSelect, "<br>";
$QuestionNumberer++;
echo $row["QuestionText"];
echo '<br>'.'Answer';
echo "<input type='text' name='answerbox[]' id='answerbox[]' class='userInfo' value='".$i."'/>";
echo '<br>'.'comment(if Applicable)';
echo "<input type='text' name='commentbox[]' id='commentbox'[]' class='userInfo' value='".$i."'/>";
}
}
else
{
echo "0 results";
}
}
I am trying to get these values from the array of names or IDs I've created but cannot figure out why I can't get it to work. I cannot even get the array of values to print
//PRINT ANSWER
echo '<br>Answer List <br>';
for($i = 0; $i < 11; $i++)
{
$_POST("answerbox[$i]");
}
Any help would be greatly appreciated. Thank you.
The short answer is that you are treating $_POST like it is a function ($_POST()) instead of an array ($_POST[]). Because your form fields are 1-dimensional arrays, your $_POST data is a 2-dimensional array. Access the submitted array elements using this syntax:
$_POST[formfieldname][numerickey]
I have rewritten a portion of your code and added some refinements which should improve efficiency and show some good practices.
$conn=new mysqli($host, $user, $pass, $dbname);
$conn->select_db('johnconn_sstest'); // designate a default database
$sql="SELECT QuestionNo,QuestionText FROM tbRandomArray ORDER BY RAND() LIMIT 10;"; // until your table gets very, very large RAND() will serve you well
if($result=$conn->query($sql)){ // declare $result and check if true/success or false/syntax failed
$i=0;
echo "<form action=\"receiving_page.php\" method=\"post\">"; // assign receiving page and data delivery method
while($row=$result->fetch_assoc()){ // loop through your db table rows
++$i;
echo "Q$i ID:{$row['QuestionNo']}<br>"; // show counter and question's row id
echo "<input type=\"hidden\" name=\"QNo[$i]\" value=\"{$row['QuestionNo']}\">"; // invisibly pass question id to receiving page
echo "{$row['QuestionText']}<br>";
echo "Answer <input type=\"text\" name=\"answerbox[$i]\" id=\"answerbox$i\" class=\"userInfo\" value=\"\"><br>"; // assign numeric key to each answer input name beginning with 1
echo "Comment(if Applicable) <input type=\"text\" name=\"commentbox[$i]\" id=\"commentbox$i\" class=\"userInfo\" value=\"\"><br><br>"; // assign numeric key to each answer input name beginning with 1
}
echo "<input type=\"submit\" value=\"Submit\">"; // submit button with no name attribute so the value is not passed to the receiving page
echo "</form>";
}else{
echo $conn->error;
}
# receiving_page.php:
if(isset($_POST["QNo"]) && sizeof($_POST["QNo"])==10 &&
isset($_POST["answerbox"]) && sizeof($_POST["answerbox"])==10 &&
isset($_POST["commentbox"]) && sizeof($_POST["commentbox"])==10){
foreach($_POST["QNo"] as $index=>$value){
// do whatever you like with the values, use $index access other arrays' elements
// $value is each QNo in sequence.
// $_POST["answerbox"][$i] is answerbox value in the same QNo row
// $_POST["commentbox"][$i] is commentbox value in the same QNo row
}
}else{
echo "Did not receive the full batch of expected values";
}
Of course, on your form, the fields' keys ($i in fieldname[$i]) can be omitted like this: fieldname[] -- this may be preferable but just be aware that then the numerickeys will start at 0 instead of 1 and will automatically increment.
print_r is your friend. You can print_r($_POST) which will let you see if you have what you think you have. Once you see that it should be clear why you aren't seeing what you want.
If this code is intended to be printing the answers, it needs to be something like
echo $_POST["answerbox[{$i}]"];

Getting two variables from one radio button?

http://i.stack.imgur.com/Gy3o0.png
That is what the site looks like now. What I want to do is when you click on the approve registration on the table, it will extract the value of the id no and the name of that particular record. I thought i was on the right track. I knew how to get the id no. But it doesn't get the value of the name at the same time.
This is how the code looks like:
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr>";
echo "<td><form method=post action=approvedmayor.php><input type='radio' name=id value='$id'></td>";
}
approvedmayor.php
$query = mysql_query("insert into tbcandidates VALUES ($id, '$name', 'mayor')");
if ($query)
{
echo "You appproved ";
echo $name;
}
else
echo "error";
you can try like this...
<?php
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr><td><a href='approvedmayor.php?id=$id&name=$name'>Approve</a></td></tr>";
}
?>
in this type don't use the form, and Approve button... try this alone
Actually it is bad practice to insert that kind of data directly from POST data.
If you have all these candidates already stored in the database, you should run a SELECT query in your approvedmayor.php first, and if the candidate still exists, insert it's data to another table.
$query = mysql_query('SELECT * FROM `candidates` WHERE `id` = '.$id.' LIMIT 1');
if(mysql_num_rows($query)) {
$candidate = mysql_fetch_assoc($query);
$insertQuery = mysql_query("insert into tbcandidates VALUES ($candidate['id'], $candidate['name'], $candidate['mayor'])");
if ($insertQuery) {
echo "You appproved ";
echo $name;
} else echo "error";
} else echo 'This candidate is no longer available';
I understand your question,
But thats not the best way go ahead, Before we move let us understand some little elements functions
Radio Button : Its an input type element, that allows the user to choose only one [ 1 ] of option given list.
Check Boxes : Its an input type element, that allows the user to select n number of options or selections from give list.
Fore info - http://www.w3schools.com/html/html_forms.asp
Now comming to your question..
You need to modify your code to check boxes as below
<input type='checkbox' name=id[] value='$id'>
Notice : elements name is in Array mode.. ie whenever a user one or more than one, the values are stored in array.
Once the values are stored in array, call it / use if however you want.
For your mentioned code
echo "<form method=post action=approvedmayor.php>';
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr>";
echo "<td><input type='radio' name=id[] value='$id'></td>";
}
echo "</form>";
approvedmayor.php
$temp_app_arr = $_POST['id'];
foreach ($temp_app_arr as $pos => $val) {
$query = mysql_query("insert into tbcandidates VALUES ('$val', '$name', 'mayor')");
if ($query) {
echo "You appproved ";
echo $name;
} else {
echo "error";
}
}
And i believe this should gonna be good code / algorithm for your project.

Categories