I am trying to populate a form based upon the option selected in the <select>. The eventTitle field in the DB has corresponding fields located at the bottom of the code. If I select option 1, I want the form to be populated with the fields corresponding to option 1. I am not sure the best way to do this. Thanks in advance.
Also, if you have any other recommendations on things I should do differently, like if I am coding a bad practice, please advise. Thanks!
require_once "functions.php";
//this creates a reference to the connection which is in the functions.php file
$connection = getConnection();
//so far this gets all the event titles and echos out a drop down list with them in. yay
$sqlPopulateQuery = "SELECT eventTitle, eventID from NE_events";
$queryResult = $connection->query($sqlPopulateQuery);
echo "Event Title: <select name='eventTitle'>";
while ($record = $queryResult->fetchObject()) {
echo "<option value='{$record->eventTitle}'>{$record->eventTitle}</option>";
}
echo "</select>";
//if a specific event is selected
//get eventID from database
//populate textfield with eventID
//echo "Event ID: <input type='text' ' name='eventID' readonly><br>";
//echo "Venue ID: <input type='text' name='venueID'><br>";
//echo "Category ID: <input type='text' name='categoryID'><br>";
//echo "Start Date: <input type='date' name='eventStartDate'><br>";
//echo "End Date: <input type='date' name='eventEndDate'><br>";
//echo "Price: <input type='text' name='eventPrice'><br>";
?>```
You can achieve your requirement with either plain javascipt or with Jquery library, below I have listed each of the methods
1.Using javascript solution
<?php
while ($record = $queryResult->fetchObject()) {
echo "<option value='{$record->eventTitle}' onChange="popuplateData({$record->eventTitle})">{$record->eventTitle}</option>";
}
echo "Event ID: <input type='text' id='eventID' name='eventID' readonly><br>";
?>
<script>
function popuplateData(option){
if(option === 'title1'){ // For each option you can modify based on value
document.getElementById('eventID').value = 'event 1';
//More fields goes here
}
}
</script>
2.Using Jquery solution
<?php
echo "Event Title: <select name='eventTitle' id='eventTitle'>";
while ($record = $queryResult->fetchObject()) {
echo "<option value='{$record->eventTitle}'>{$record->eventTitle}</option>";
}
echo "</select>";
echo "Event ID: <input type='text' id='eventID' name='eventID' readonly><br>";
?>
<script>
jQuery(document).ready(function($) {
$("#eventTitle").change(function(){
var optionVal = $(this).val();
if(optionVal != ''){
if(optionVal === 'title1'){// For each option you can modify based on value
$('#eventID').val('event 1');
//More fields goes here
}
}
});
});
</script>
Related
So, I need to make sure this sets the right parameters to the DB when pressing the buttons. I just want to get the calls and comparisons right so it does what it should when I hit the buttons. There should be one delete button for each row from database, and update page when I press it.
It should be possible to update the text/numbers in the forms presented by MySQL by changing the forms and press Save-button, then refresh the page.
$counter = 1;
if(isset($_POST['save']) and something is changed from the forms compared to DB) {
Update MySQL
Refresh page
<script>
window.location.replace("thispage.php");
</script>
}
if(isset($_POST['del'])) {
DELETE MySQL
Refresh page
<script>
window.location.replace("thispage.php");
</script>
}
echo "<tr><td>ID</td><td>Namn</td><td>Platser</td><td>Fullbokad</td><td>Ta bort</td></tr>";
$sqlListSections = "SELECT * FROM avdelningar WHERE user = {$_SESSION['id']}";
$queryListSections = mysqli_query($mysqli, $sqlListSections);
$del = [];
while($rowListSections = mysqli_fetch_array($queryListSections))
{
if($counter%2)
{
echo "\n<tr bgcolor=#F1F1F2>\n\n";
}else
{
echo "\n<tr bgcolor=#FFFFFF>\n\n";
}
$counter++;
echo "
<td>".$rowListSections['id']."</td>
<td>
<input type=text value=".$rowListSections['namn']."></td>
<td>
<input type=text value=".$rowListSections['platser']."></td>
<td>";
if($rowListSections['prio'] == 1)
{
echo "<select name=platser>
<option selected value=".$rowListSections['prio'].">".$rowListSections['prio']."</option>
<option value='0'>0</option>".$rowListSections['prio'];
}elseif($rowListSections['prio'] == 0)
{
echo "<select name=platser>
<option selected value=".$rowListSections['prio'].">".$rowListSections['prio']."</option>
<option value='1'>1</option>".$rowListSections['prio'];
}
echo "</td>
<td>
<form method=post action=thispage.php>
<input type=submit value=Delete name=del>";
</td>
</form>
</tr>";
}
echo "<form method=post action=thispage.php>
<input type=submit value=Save name=save>";
`
in your checkbox change naming as array.
<input type=checkbox name="del[]" value={$rowListSections['id']}>
like
echo $rowListSections["id"].' '.$rowListSections["namn"].' '.$rowListSections["platser"].' '.
$rowListSections["prio"].'';
and in your if(isset($_POST)) you can get a del array so you can loop this array like below.
foreach($del as $val){
$id = $val;
$sql_query_for_update = "update table_name set field = 1 where id= '$id' ";
}
I want to pass the value for each rows to php page to update in database I am able to pass only id not the input box value
This is the table body
<?php
$cards = mysqli_query($con,"SELECT Username, Card_No, Card_Status FROM
smartcard WHERE Card_Status NOT IN (SELECT Card_Status FROM smartcard where Card_Status = 'Issued')");
?>
<tbody>
<?php
while ($row = mysqli_fetch_assoc($cards))
{
echo '<tr>';
foreach ($row as $key => $value) {
echo '<td style="word-wrap: break-word;min-width: 10px;max-width: 300px;">',$value,'</td>';
}
echo '<td><form action="php/issue_card.php" method="POST"><input id="textbox" name="new_status" type="text" class="form-control" required="required"/></form></td>';
echo "<td>Status Update</button></td>";
echo '</tr>';
}
?>
</tbody>
This is the php page issue_card.php
<?php
include("connect.php");
$con = OpenCon();
$smartcard_no = $_GET['id'];
$admin_id = $_SESSION['Admin_Id'];
$new_status = $_POST['new_status'];
$sql = "UPDATE smartcard SET Card_Status = '$new_status', Admin_Id ='$admin_id' WHERE smartcard.smartcard_no = $smartcard_no";
mysqli_query($con, $sql);
CloseCon($con);
?>
For each row there will be different smartcard_no so I am using anchor tag to pass that directly using GET but not able to pass input box value.
<?php
$cards = mysqli_query($con,"SELECT Username, Card_No, Card_Status FROM
smartcard WHERE Card_Status NOT IN (SELECT Card_Status FROM smartcard where Card_Status = 'Issued')");
?>
<tbody>
<form>
<?php
while ($row = mysqli_fetch_assoc($cards))
{
echo '<tr>';
foreach ($row as $key => $value) {
echo '<td style="word-wrap: break-word;min-width: 10px;max-width: 300px;">',$value,'</td>';
}
echo '<td><input class="textbox" name="new_status" type="text" class="form-control" required="required"/></td>';
echo "<td><button class="updateBtn" data-id=".$row['Card_No'].">Status Update</button></a></td>";
echo '</tr>';
}
?>
</tbody>
<script>
/*import jquery before using this.*/
$(document).ready(function(){
$('.updateBtn').on('click',function(){
var status=$(this).parent().find('.textbox').val()
var id=$(this).attr('data-id');
sendData(status,id)
})
function sendData(status,id){
$.ajax({
url:'php/issue_card.php',
data:{status:status,id:id},
type:'get' //get or post,
success:function(success){
//callback
},
error:function(error){
//error callback
}
})
}
})
</script>
The following is a quickly written ( and not tested ) example of the 2nd idea - where there is just one form that encompasses the entire table and has two hidden fields for the important pieces of data that you wish to POST to the PHP script.
Each button within the table is assigned an event handler - the event handler in this case will query the DOM to find the text field within the same row and then assign that value and the value found in the buttons own data-id attribute o the hidden input fields before submitting the form.
<script>
document.addEventListener('DOMContentLoaded',function(e){
/* Obtain a reference to the FORM element */
var form=document.forms['status-updates'];
/* Hidden fields which will be POSTed to php/issue_card.php */
var id=form.querySelector('input[type="hidden"][name="id"]');
var status=form.querySelector('input[type="hidden"][name="new_status"]');
/* Create a nodelist collection of ALL buttons within table of class "bttn" */
var col=Array.prototype.slice.call( form.querySelectorAll('input[type="button"].bttn') );
/* Assign event handler to each button */
col.forEach( function( bttn ){
bttn.onclick=function(e){/* - event handler - */
/* Assign values to hidden fields */
id.value=this.dataset.id;
status.value=this.parentNode.querySelector('input[type="text"]').value;
/* submit the form with values for this row */
form.submit();
}.bind( bttn );
});
},false );
</script>
<form name='status-updates' method='post' action='php/issue_card.php'>
<!-- two hidden fields -->
<input type='hidden' name='id' />
<input type='hidden' name='new_status' />
<table>
<?php
while( $row = mysqli_fetch_assoc( $cards ) ) {
echo "
<tr>";
foreach( $row as $key => $value ) echo "
<td class='wrap'>{$value}</td>";
echo "
<td>
<input type='text' class='form-control' required='required' />
<input type='button' value='Status Update' class='bttn' data-id='{$row['Card_No']}' />
</td>
</tr>";
}
?>
</table>
</form>
I want to fetch data from dropdown list. Like if I choose employee id 40 from the dropdown list it will fetch the data from database of that employee and will shown in the textboxes.
this is my dropdown code. please help me how can i get the selected value.
<?php
$con=mysqli_connect("localhost","root","","hct_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<label>Select Employee ID</label>
<select class="form-control" name="employee_id">
<?php
$result = mysqli_query($con,"SELECT employee_id FROM employee order by employee_id");
while($row = mysqli_fetch_array($result))
echo "<option value='" . $row['employee_id'] . "'>" . $row['employee_id'] . "</option>";
?>
</select>
First of all give some id to you select option like this:
<select class="form-control" name="employee_id" id='employee'>
Add you textbox like this:
<input type='text' name='emp_name' id='emp_name' />
Than use jquery and ajax something like this:
$('#employee').change(function(){
var selected_id = $(this).val();
var data = {id:selected_id};
$.post('getemp_name.php',data,function(data){
$('#emp_name').val(data);
});
});
getemp_name.php
if(isset($_POST['id'])){
//fire query using this id and get the name of employee and echo it
echo $emp_name;
}
<?php
if(isset($_REQUEST['submit']))
{
$value=$_POST['employee_id'];
$query = mysql_query($con,"SELECT employee_name FROM employee where employee_id=$value");
$result=mysql_fetch_array($query);
$emp_name=$result['employee_name'];
}
?>
<form action="" method="post" name="form">
<label>Select Employee ID</label>
<select class="form-control" name="employee_id">
<?php $result = mysqli_query($con,"SELECT employee_id FROM employee order by employee_id");
while($row = mysqli_fetch_array($result))
echo "<option value='" . $row['employee_id'] . "'>" .$row['employee_id'] . "</option>";
?>
</select>
<input type="submit" name="submit" value="submit">
</form>
<input type="text" value="<?=$emp_name?>" name="emp_name"/>
check this code as your need
To get your selected value, you have to reach the $_GET or $_POST supertables after the user submits the form.
So, after the submit, get it as, if you POST:
<?php
$employee_id = $_POST['employee_id']; ?>
If you GET:
<?php
$employee_id = $_GET['employee_id']; ?>
apply below function on onChange
function myFunction(mySelect) {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
example
That depends on what you want. If you want to use the selected ID in your query AFTER DOING A POST, you can use the following query:
"SELECT *
FROM `employee`
WHERE `employee`.`employee_id` = " . (int) $_POST['employee_id'] . "
LIMIT 1"
Assuming you are using the post method in your form.
You can easily learn how to fetch data from dropdown using this example by clicking Here This repository contains all the codes
Actually I am very new to php.. I have a task that select records from database as checkboxes checked. When I uncheck a checkbox it should delete that particular record from my database..
My code is
<?php
if(isset($_POST['delete']))
{
$test=$_POST['test'];
$qun1=$_POST['question1'];
//DB connection
$CON=mysql_connect("localhost","root","");
mysql_select_db("Dbname");
if($qun1!=0 && $test!=0)
{
foreach($qun1 as $qunestion)
{
echo $question; //this is for testing
$query=mysql_query("delete from test_question where test_questions_id='$test' AND question_id IN ('$question') " ) or die(mysql_error());
}
if($query)
{
echo "success";
}
else
{
echo "No";
}
}
}
?>
my code is working properly but if i use NOT IN in the place of IN it is not working..why?..if unchecked the records it should be delete..i already retrieve records from database as checked fields..
My html markup:
<script>
function fun2(ts)
{
$.post("ajax2.php",{qs:ts},function(data)
{
document.getElementById('div1').innerHTML=data
})
}
</script>
<form action="somepage.php" method="post">
//dynamic selection test code
<select name="test" id="test" onChange="fun2(this.value);">
<option value="">Select Test</option> </select>
<div id="div1" > </div>
<input type="submit" name="delete" value="Delete" >
</from>
my ajax code:
<?php
$qs=$_REQUEST['qs'];
mysql_connect("localhost","root","");
mysql_select_db("advancedge");
$sql=mysql_query("select question_id from test_question where test_questions_id='$qs'");
if($sql)
{
while($rec=mysql_fetch_row($sql))
{
echo "<input type='checkbox' name='question1[]' value='$rec[0]' checked='checked' >";
}
}
?>
If I understand correctly, you want to delete as soon as the item is unchecked? To check if a checkbox is unchecked, you have to use javascript. PHP runs on the server, not the client side (you could use ajax, but I would recommend not to for this).
I would recommend, you delete whatever you want to on form submission, if you don't know how to do that,I can tell you if you post the html part up.
I would also recommend you learn PHP from a course on the internet, so you know some standards and get some good practices. (Youtube or Lynda.com)
It is an old post, but if someone end up here - this might solve the problem:
<?php
echo "<form action='' method='post'>";
echo "<input type='checkbox' id='chk_1' name='chk_1' value='First' />chk 1 </br>";
echo "<input type='checkbox' id='chk_2' name='chk_2' value='Second' />chk 2 </br>";
echo "<input type='submit' />";
echo "</form>";
$check = array();
// Set all checkboxes to 0 if unchecked
for($i = 1; $i<=2; $i++) {
$check["chk_$i"] = isset($_POST["chk_$i"]) ? 1 : 0;
}
// Output of the array
echo '<pre>';
var_export($check);
echo '</pre>';
The code will set all unchecked checkboxes to 0.
Then you have to take care of that using something like this:
<?php
if($_GET['chk_1'] == 0) {
$sql = "DELETE FROM mytable WHERE...";
}
I've been at this the whole day. First I tried to validate my form in php but finally gave up. Now I'm trying to validate the form with JavaScript. It works but since I don't know JavaScript at all and have limited knowledge of PHP I really need help please. It is a test and I want to validate that each question has been answered. The field name in the form = php variable/array, can't get this to work in the javascirpt
var x=document.forms["myForm"]["question_{$q_nr}"].value;
. If I just use a text field name it works fine.
The form
<html>
<head>
<?php
session_start();
?>
<script type="text/javascript" src="counter.js"></script>
<script language="JavaScript">
<!--
function validateForm()
{
var x=document.forms["myForm"]["question_{$q_nr}"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
//-->
</script>
</head>
<body>
<?php
if ($_SESSION['auth']) {
$tid = $_GET['tid'];
echo "<span id='counter'></span>";
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid' ORDER BY q_nr";
$result1=mysql_query($sql1);
echo "<form name='myForm' action='http://localhost/index.php?option=com_content&view=article&id=51' onsubmit='return validateForm()' method='post'>";
while($row1 = mysql_fetch_array($result1))
{
$q_nr=$row1['q_nr'];
$q_type=$row1['q_type'];
$question=$row1['question'];
$option1=$row1['option1'];
$option2=$row1['option2'];
echo "<P><strong>$q_nr $question</strong><BR>";
echo "<img src='images/tests/$pic'>";
echo "<BR>";
echo "<BR>";
echo "</p>";
if ($q_type != 'mr') {
if($option1!="") {
echo "<input type='radio' name='question_{$q_nr}' value='A'>$option1<BR>";
} else {
echo ''; }
if($option2!="") {
echo "<input type='radio' name='question_{$q_nr}' value='B'>$option2<BR>";
} else {
echo ''; }
} else { // else if not <> mr
if($option1!="") {
echo "<input type='checkbox' name='question_{$q_nr}[]' value='A'>$option1<BR>";
} else {
echo ''; }
if($option2!="") {
echo "<input type='checkbox' name='question_{$q_nr}[]' value='B'>$option2<BR>";
} else {
echo ''; }
} //if q_type <> mr
} //while row1
echo "First name: <input type='text' name='fname'>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
} //else if now > testend
} //if ses auth
?>
why do you think so complicated ?
just use unique ID's for each label, input field, etc ... and check for the innerHTML or value stored; and also you can change the values whenever you want;
btw, your code is messy;
write your code like this:
zone 1: all the js goes here
zone 2: all the html goes here
zone 1:
<script language="text/JavaScript">
//alljs code here
function validate()
{
if( document.getElementById('unique_2').value == null ) document.getElementById('unique_3').innerHTML = 'error1';
if(document.getElementById('unique_4').value == null ) document.getElementById('unique_6').innerHTML = 'error 2';
}
</script>
zone 2:
<form onsubmit="validate()">
all html label and fields go here, like:
<label id="unique_1">label text</label>
<input type="text" id="unique_2" value="" />
<label id="unique_3"></label> this is for the error message
<label id="unique_4">label text</label>
<input type="text" id="unique_5" value="" />
<label id="unique_6"></label> this is for the error message
</form>
This is simple JQuery validation.
I think you must have both validation if you want to be secured...
p.s. Just add 'required' in class of input if you want to be required...
Well for one thing -- validating on the server side is the way to go.
If you just validate on the client side, it can be futzed with (a lot)