Submission of radio button variable in php - javascript

I am writing a program which will display a list students of a class and in front of each student name there are three radio button for Absent, present and on leave.
The list of student is generated with while loop. Now I want to pass the value of radio button through a variable like this.
echo "<tr>"
. "<td>$id</td>"
. "<td>$name</td>"
. "<td><input type=radio name=$name value=P></td>"
. "<td><input type=radio value=L name=$name></td>"
. "<td><input type=radio name=$name value=A></td>"
. "</tr>";
Is this possible to send value of radio button like this?

Yes, but please do note that your input attributes should have single/double quotes.
echo "<input type=radio name='$name' value='p' />";
or you can escape double quotations like this
echo "<input type=radio name=\"$name\" value=\"P\">";
or concatenate php variables
echo '<input type=radio name="'.$name.'" value="P">";
UPDATE:
Checking each student's profile
Inside your while loop create an array name. An array name is like this, it has square brackets after the string 'attendance'.
<input name="attendance[]" />
Now, for each student's row. Assign the student ID inside the array name.
echo "<tr>"
. "<td>".$id."</td>"
. "<td>".$name."</td>"
. "<td><input type='radio' name='attendance[".$id."]' value='P'></td>"
. "<td><input type='radio' name='attendance[".$id."]' value='L'></td>"
. "<td><input type='radio' name='attendance[".$id."]' value='A'></td>"
. "</tr>";
Putting the $id inside your array name will serve as your pointer, use it in your backend to update each student's attendance status.
foreach ($_POST['attendance'] as $key => $value) {
//$_POST['attendance'] variable is an array.
//Where $key variable is your Student ID, use this to update their status
//Where $value is a student's selected attendance status.
echo 'Student ID:'. $key . ' is '. $value . '<br>';
//Update a student's attendance status using $key as their id.
}
You can also simulate this code I made: http://viper-7.com/Tb1lbo

Yes, this is possible. Code:
<?php
$students = [
[
'id' => '1',
'name' => 'Amy'
],
[
'id' => '2',
'name' => 'Bob'
],
[
'id' => '3',
'name' => 'Charlie'
]
];
echo
'<form action="' . $_SERVER['PHP_SELF'] . '" method="post">' .
'<table>' .
' <thead>' .
' <tr>' .
' <th>Student Id</th>' .
' <th>Student Name</th>' .
' <th>Attendance (P / L / A)</th>' .
' </tr>' .
' </thead>' .
' <tbody>';
foreach ($students as $student) {
echo
' <tr>' .
' <td>' . $student['id'] . '</td>' .
' <td>' . $student['name'] . '</td>' .
' <td>' .
' <input type="radio" name="attendance_' . $student['id'] . '" value="P" />' .
' <input type="radio" name="attendance_' . $student['id'] . '" value="L" />' .
' <input type="radio" name="attendance_' . $student['id'] . '" value="A" />' .
' </td>' .
' </tr>';
}
echo
' <tr>' .
' <td colspan="3">' .
' <input type="submit" name="submit" value="Attendance" />' .
' </td>' .
' </tr>' .
' </tbody>' .
'</table>' .
'</form>';
if (isset($_POST['submit'])) {
echo '<pre>' . print_r($_POST, true) . '</pre>';
}
And on form submit:
Array
(
[attendance_1] => P
[attendance_2] => L
[attendance_3] => L
[submit] => Attendance
)

First you need to include single or double quotes around the name like this:
<tr><td>$id</td><td>$name</td><td><input type='radio' name='$name' value='P'></td><td><input type='radio' value='L' name='$name'></td><td><input type='radio' name='$name' value='A'></td></tr>";
You can then use the name of the radio button group to get the value from the $_POST or $_GET superglobal depending on your request type.
$name = 'name_of_the_radios'
$studentPresence = $_POST[$name] //For get requests use $_GET
if($studentPresence == 'P')
{
//Student is present
}
else if($studentPresence == 'A')
{
//Student is absent
}
else if($studentPresence == 'L')
{
//Student is on leave
}
else
{
throw new Exception("Invalid student presence argument');
}

Related

PHP wrong database edit

I'm setting up a dynamic webpage that will be used as a time stamp for employes. After you log in, you will write down when you started work, how long the break was, when you finished and so on..
Problem is that every time I wanna change something on the webpage, for example I want to change my break time, it won't change and shows me the user_id instead.
I'm still a beginner when it comes to PHP and don't know where the problem is..here are some code snippets
<div class="header">
<ul>
<li>
<p class="text">HourBook</p>
</li>
</ul>
</div>
<table class="table table-striped table-bordered">
<tr>
<th class="luecke1">Name</th>
<th class="luecke2">Start Time</th>
<th class="luecke3">Pause</th>
<th class="luecke4">End Time</th>
<th class="luecke5">Comments</th>
<th class="luecke6">Duration</th>
</tr>
<?php
$connect = new mysqli('localhost', 'root', '', 'hourbook');
$result = $connect->query("SELECT * FROM data");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
echo "<tr>";
echo "<td class='luecke1'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['user_id'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"user_id\"})'></input></td>";
echo "<td class='luecke2'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['start_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"start_time\"})'></input></td>";
echo "<td class='luecke3'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['pause_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"pause_time\"})'></input></td>";
echo "<td class='luecke4'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['end_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"end_time\"})'></input></td>";
echo "<td class='luecke5'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['comments'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"comments\"})'></input></td>";
echo "<td class='luecke6'><input style='border:none; width:100%; background:rgba(0,0,0,0)' contenteditable='true' id='editor" . $id . "' value='" . $row['total_time'] . " ' onchange='pruefung({currentid:" . $id . ",currentfieldname:\"total_time\"})'></input></td>";
}
} else {
echo "No results!";
}
?>
<script>
var oldValue;
function pruefung(params) {
var newValue = document.getElementById('editor' + params.currentid).value; //editor id verknüpfung falsch?
if (oldValue == newValue) {
console.log("no changes");
} else {
console.log("changes");
$.ajax({
url: "update.php",
type: "POST",
data: {
value: newValue,
id: params.currentid,
fieldname: params.currentfieldname
},
success: function(data) {
alert("Saved successfully!");
document.location.reload(true);
},
error: function(data) {
alert("error: " + data);
}
})
}
}
</script>
</table>
In your AJAX call you have : var newValue = document.getElementById('editor' + params.currentid).value;
In your table, for each row you have : id='editor" . $id . "'. This is a duplicate of ids.
When doing var newValue = document.getElementById('editor' + params.currentid).value; You are getting the first element that has this id, that's why newValue is always the id (the first row holding the id value)
I suggest you to remove that var newValue = ... but instead insert the value in the object you pass as parameter of pruefung(), such as onchange='pruefung({currentid:" . $id . ",currentfieldname:\"user_id\",value:\"" . $row['user_id'] . "\"}) for the id row, onchange='pruefung({currentid:" . $id . ",currentfieldname:\"user_id\",value:\"" . $row['start_time'] . "\"}) for the start time row, and so on...
And then, in your AJAX call, replace var newValue = document.getElementById(...) by var newValue = params.value

Choose an amount of certain item from the database to save into a variable

I'm trying to make a way to take a certain quantity of a product from all displayed from the database, for example I want to take 3 out of 5 possible ones with me but I have no idea what I need to add to make it so, right now it displays the data like this:
foreach ($order->get_items() as $item ){
$unitprice = $item->get_total() / $item->get_quantity();
echo "<input type='checkbox' name='productinfo[]' value='" .$item->get_name() . "|" . $item->get_quantity() . "|" . $item->get_total() ."'>";
echo '<p>';
echo __('Product name: ' ) . $item->get_name() . '<br>';
if($item->get_quantity() > 1) {
echo "Amount: " . "<input type='number' name='numberqty' value='" . $item->get_quantity() . "'max='" .$item->get_quantity() . "' min='0' > " . "<br/>";
}
else {
echo __('Amount: ' ) . $item->get_quantity() . '<br>';
}
echo __('Product individual price: ') . $unitprice . '€' . '<br/>';
echo __('Product total: ' ) . wc_price($item->get_total()) . '</p>' . '<br/>';
}
echo '<p>'. __('Order total: ') . $order->get_total() . '</p>';
I'm not very good at making questions so ask if something is unclear.

Displaying the other values in the table on select option from database

i have a select option, after selecting a brand I successfully get/display the brand name but I want also the other values be displayed like price, with or without refreshing the page.
<?php
require_once 'config.php';
echo '<select class="form-control action" name="tran_description" value="<?
php echo $tran_description; ?>" style="background-color:#F0F0F0">';
$sql = mysqli_query($mysqli, 'SELECT * FROM products order by product_id');
while ($row = $sql->fetch_assoc()){
echo '<option id="' . $row['product_id'] . '"';
echo ' value="' . $row['description'] . '" ';
echo ' value="' . $row['price'] . '" ';
if($row['description'] == $tran_description) {
if($row['price'] == $tran_price) {
$tran_price = $row['price'];
echo ' selected="selected"';
}
}
if($row['product_id'] == $row['description']) {
echo ' selected="selected"';
}
echo '>';
echo $row['description'];
echo '</option>';
}
echo '</select>';
?>
I can get the value of the description but the price I couldnt. In one select option representing the brand or description I want also the price value of that brand I selected be assign to a variable so I can do arithmetic operation in the back code without seeing it.Thanks.
You are using wrong HTML structure only the first attribute is being used while the other is being ignored in the DOM .The right way to store multiple values in a single select can be like this:
<select name="">
<option value="{'num_sequence':[0,1,2,3]}">Option one</option>
<option value="{'foo':'bar','one':'two'}">Option two</option>
</select>
In your case it should be like this:
echo '<option id="' . $row['product_id'] . '"';
// echo ' value="{ /"description:/"' . $row['description'] . ', /"price:/"' . $row['price'] . ' }" ';
echo ' value="' .
json_encode(['description'=>$row['description'], 'price'=>$row['price']) .
'">";
Then to get the value you'll do is:
$description = $_POST['NameOfSelectInput']['description'];
$price = $_POST['NameOfSelectInput']['price'];
If you want to get the value in javascript, using jQuery, for example, you could do:
var value = JSON.parse($('#select_id').val()); // use id of your select control
var price = value.price;
var description = value.description;
You should do appropriate error checking...
For more details refer here:
Can an Option in a Select tag carry multiple values?

JS sequential calling of function fails

I need to exicute one JS function after another sequencually. I can exicute these functions individually and they work but when I put them in a sequence I only get the openPatient() and the openMessage() does not exicute. My JS functions
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
My function call:
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
This function call exists in this process:
<?php
// Generate a table row for each pending portal request or message.
// This logic merges requests with messages by date.
$v1 = each($result['list']);
$v2 = each($result['messages']);
while ($v1 || $v2) {
echo " <tr class='detail' bgcolor='#ddddff'>\n";
if (!$v2 || $v1 && $v1[1]['datetime'] < $v2[1]['datetime']) {
$postid = $v1[1]['postid'];
$ptname = patientNameFromLogin($v1[1]['user']);
// Get the portal request data.
if (!$postid) die(xlt('Request ID is missing!'));
$result2 = cms_portal_call(array('action' => 'getpost', 'postid' => $postid));
if ($result2['errmsg']) {
die(text($result2['errmsg']));
}
// Look up the patient in OpenEMR.
$ptid = lookup_openemr_patient($result2['post']['user']);
echo " <td>" . text($v1[1]['user']) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;' onclick=\"openPatient()\">" .text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
echo " <td>" . text($v1[1]['type' ]) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_req_cb[" .
attr($postid) . "]' value='" . attr($postid) . "' /></td>\n";
$v1 = each($result['list']);
}
else {
$messageid = $v2[1]['messageid'];
$ptname = patientNameFromLogin($v2[1]['user']);
echo " <td>" . text($v2[1]['user']) . "</td>\n";
echo " <td>" . text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openMessage(" .
"'" . addslashes($messageid) . "'" .
")\">" . text($v2[1]['datetime']) . "</td>\n";
echo " <td>" . text($v2[1]['user'] == $v2[1]['fromuser'] ?
xl('Message from patient') : xl('Message to patient')) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_msg_cb[" .
attr($messageid) . "]' value='" . attr($messageid) . "' /></td>\n";
$v2 = each($result['messages']);
}
echo " </tr>\n";
}
?>
I am thinking part of the problem may be that openPatient() opens in another window. Perhaps it is loosing focus. Any tips to fix this would be appreciated.
EDIT:
What I have tried and helps is adding return this; to openPatient():
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
This then executes the next function but the next function executes too soon. it needs to wait for openPatient() to fully load before executing openMessage(). I have tried adding setTimeout( wait, 1000 ); but then openMessage() does not execute at all.
The solution:
The call:
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient();setTimeout(function(){openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
")}, 2500);\">" . text($v1[1]['datetime']) . "</td>\n";
The functions:
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
Keys to success: return this; and the use of the anonymous function with setTimeout in the call.
Posts that helped:
What does "return this" do within a javascript function?
setTimeout delay not working

passing variable from while loop when user press link (php)

i am searching for a way to pass variable ($result[1]) to a session variable from while loop within a link. will be glad for some help
while ($result = mysqli_fetch_array($dataset,MYSQLI_NUM)){
echo "<tr>";
echo " <td >", "<a href='Rate_Supplier.php'>" . $result[1] ."
</a>","</td>" ;
echo " <td >" . $result[0] . "</td>" ;
echo " <td >" . $result[2] . "</td>" ;
echo "</tr>\n";
}

Categories