filtering table by choosing in combobox - php

I need to get the list of diagnosed disease of the patient by choosing his name in the combo box, how can I do that? This is my code.
<select name="pname" class="textfields" id="model" style="width:180px;" onchange="getVal1();">
<option id="0" >--Select Patient Name--</option>
<?php
$con = mysqli_connect("localhost","root","","dbnpatient");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pnum = $_GET['pnum'];
$query = mysqli_query($con, "SELECT * FROM tblnpatient");
while($row = mysqli_fetch_array($query)){
$pnum = $row['pnum'];
$pname = $row['pname'];
$addr = $row['addr'];
$complaints = $row['complaints'];
?>
<option id="<?php echo $pnum; ?>" data-pnum="<?php echo $pnum; ?>" data-addr="<?php echo $addr; ?>" data-complaints="<?php echo $complaints; ?>" value="<?php echo $pname; ?>"><?php echo $pname; ?></option>
<?php } ?>
This is my code for filtering the table: And i having a trouble in this code because nothings appear in the table when i select the pname
<?php
$con = mysqli_connect("localhost","root","","dbnpatient");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pname = $_GET['pname'];
$result = mysqli_query($con,"SELECT * FROM tbldiagnosis WHERE pname='$pname'");
while($row = mysqli_fetch_array($result)) {
echo '<tr class="record">';
echo '<td>'.$row['diagnosis'].'</td>';
}
?>

This can be easily done using ajax. On change of the select, you can trigger a jQuery call to submit the selected value of the box to your PHP page, which has the MySQL to filter the table. The returned result will then be displayed on the page in the designated area.
Main Page:
<select name="pname">
<option value="pname-value">pname-value</option>
</select><br>
<div id="query_results"></div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="pname"]).on('change',function() {
var curPname=$(this).val();
$.ajax({
type:'GET',
url:'urltotable.php?pname='+curPname,
success:function(data) {
$("div#query_results").html(data);
}
});
});
});
</script>
This is a simplified ajax call that will grab the value from the select box named "pname" and it will send that value to the "url" variable in the ajax call via "GET". This page can then take that variable via GET and use it to get the query results. Upon successful completion, it will display the results inside the div we added with the ID of "query_results".
You can easily customize the select to use your current PHP as listed above, also.
Now for the "urltotable.php" as we specified above, you can use the table query you have above, but just be sure to add the GET line to it so that your pname variable is accessible to the script:
$pname=$_GET["pname"];
For more information about Ajax for full features list, click here to read about Ajax in the jQuery documentation.

Related

Populate Table from more than one drop-down list

I'm trying to populate a Table after a user picks options from a drop down list when this options are picked the table should be populated based on selected options. I'm not sure how can I get this done and I've searched for tutorias etc but nothing helped me. So I'll be glad if someone can help somehow for example with small test codes etc.
I'm using PHP and the options for the drop-down list come from a MySQL-Database so in summary a person will choose a user from Users-drop down list after that a another option from different drop down list and then there's also going to be a date filter after 1, 2 or all 3 are selected a table will be produced based on the selected values.
So far I've no code done because I have no idea how to do it but I guess I need to put all 3 dropdown lists in a form and after submission I should produce the table, but how can I have more than one <select> ..... </select> in a <form> and submit them all simultaneously.
What I've done so far (I know it's unsafe and that mysql_* doesn't exist anymore in PHP7) but please don't criticize it.
UPDATE
//Database query for User drop-down(DD) population.
$sqlDD = " SELECT DISTINCT `user` FROM `users` " ;
$resultDD = mysql_query($sqlDD);
//Database query for Status drop-down(DD) population.
$sqlDDStatus = " SELECT `status` FROM `status` WHERE `id` = 1 OR
`id` = 123 OR `id` = 182 OR `id` = 12 ";
$resultDDStatus = mysql_query($sqlDDStatus);
<form id="form1" name="form1" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<select name="userSelect">
<?php
while($rowDD = mysql_fetch_array($resultDD)):
echo "<option value='" . htmlspecialchars($rowDD['user']) ."'>" . htmlspecialchars($rowDD['user']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<!-- Second DD-list in the same form -->
<select name="Status" style="max-width: 250px;" >
<?php
while($rowDDS = mysql_fetch_array($resultDDStatus)):
echo "<option value='" . htmlspecialchars($rowDDS['status']) ."'>" . htmlspecialchars($rowDDS['status']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<input type="submit" name="submit" value='Find'/>
</form>
//Get the submited data
<?php if(isset($_POST['submit'])): ?>
<?php echo 'This is submitted ' . $_POST['submit']; ?>
<?php endif; ?>
I've added echo 'This is submitted ' . $_POST['submit'];
because i wanted to see what is submitted but all it get's echoed out is only
"Find".
Any ideas how can i get the data submitted from both 's in the form and populate a table based on it ?
UPDATE 2
After getting an answer from other users I saw that my forms handles the data correctly but my question now is how can I use the data from the Submitted DDL Form and populate a table with them? So far I've tried the following:
<?php if(isset($_POST['submit'])): ?>
<?php $result = mysql_query( "SELECT * FROM `users` WHERE `user` =
$_POST['userSelect'] AND (`id` = 1 OR `id` = 18)" );
?>
<?php endif; ?>
and then in the table
<table>
<?php while ($row = mysql_fetch_assoc($result)) :; ?>
<tr>
<td><?php echo $row['user']; ?></td>
<?php endwhile; ?>
</table>
But I just don't get any response when I try it. How can I fix my problem and get the wanted output?
EDIT
I think that i've found my mistake after some research im not able to test the code now but i'm almost positive that you can't use $_POST['userSelect'] in the Database query so i just need to assign $_POST['userSelect'] to some variable before i use it in the query. So far i've gotten useful 1 little useful tip...... so disappointed from stackoverflow .......
This is a basis HTML/PHP page for getting data from the backend to the frontend, this should get you started. Try to print the data (in the while loop on the HTML page).
<html>
<head>
<title></title>
</head>
<body>
<form action="dropdown.php" method="POST">
<select name='options'>
<option>option 1</option>
<option>option 2</option>>
<option>option 3</option>>
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}else{
if (!empty($_POST)){
if(!empty($_POST['options'])){
$option = $_POST['options'];
$query = "SELECT * FROM table WHERE option='$option'";
$res = $mysqli->query($query);
while($data = $res->fetch_assoc()){
//print data to HTML page
print_f('%s, $s\n', $data['firstname'], $data['lastname']);
}
}
}
}
?>
Your form is probably working, the reason you only get "Find" is because you are printing the value of the submit button.
To get an overview of your form data, try:
echo '<pre>';
print_r($_POST);
echo '</pre>';
You will get the other values of your form by using the name attribute of your <select> with $_POST:
echo $_POST['userSelect'];
echo $_POST['Status'];
By the way, you are using a deprecated extension (written here for example), it is recommended to use MySQLi or PDO (especially PDO is recommended). If you are working with PHP 7, mysql_connect won't work as it has been removed.
And I'm not sure the use of htmlspecialchars() is relevant on each database data you use.
PHP.net - print_r() (See also var_dump())
PHP.net - $_POST

use drop down menu to query mysql

Beginner here; I have searched many examples, still need some help.
I would like for the user to select an option from a dropdown box, and that option will query a table in mysql. I don't understand how to (in my html file) show the select statment in getprojectstatus.php.
<html>
<head>
<title>Status Dashboard</title>
</head>
<body style="background:#19245e url('images/fade.png')repeat-x;font-size:12px;font-family: Arial;line-height:18px;color:#FFFFFF;">
<script>
function displayProject(option)
{
var x;
if (option=='sciplay')
{
x="show Sciplay selected, show notes, status, etc..."
}
else if (option=='oklahoma')
{
x="show OK selected, show..."
}
else if (option=='northdakota')
{
x="show North Dakota selected, show..."
}
else if (option=='audit')
{
x="show Audit selected, show..."
}
else if (option=='sggaming')
{
x="show SG Gaming selected, show..."
}
else if (option=='all')
{
x="..."//(option=(1+2+3+4+5))
}
document.getElementById("demo").innerHTML=x;
}
</script>
<div align="center">
<TABLE BORDER="1">
<TR>
<TD><img src='images/header.png'/>
</TD>
</TR>
<TR>
<TD>
<TABLE BORDER="0" bgcolor="C0C0C0" align="left">
<TH>Projects
</TH>
<TR>
<TD>
<FORM action="getprojectstatus.php" method="post">
<SELECT onload="displayProject(this.value);" onchange="displayProject(this.value);">
<OPTION VALUE='all'>ALL</OPTION>
<OPTION VALUE='sciplay'>Sciplay</OPTION>
<OPTION VALUE='oklahoma'>Oklahoma</OPTION>
<OPTION VALUE='northdakota'>North Dakota</OPTION>
<OPTION VALUE='audit'>Audit SSAE16</OPTION>
<OPTION VALUE='sggaming'>SG Gaming</OPTION>
</SELECT>
</FORM>
</TD>
</TR>
</TABLE>
</TD>
</TR>
<TR>
<TD>
<p id="demo">
</p>
</TD>
</TR>
</TABLE>
</div>
</body>
and my getprojectstatus.php file:
<?php
//create connection variables
$host=`localhost`;
$user=`dashboard`;
$pw=`password`;
$db=`status`;
//create connection
$con=mysqli_connect("$host", "$user", "$pw", "$db");
//check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//take input from form and store as var queries
$option= $_POST['option'];
if ($option == 'sciplay')
{
$queries = "SELECT * FROM status where project=1"
}
else if ($option == 'oklahoma')
{
$queries = "SELECT * FROM status where project=2"
}
else if ($option == 'northdakota')
{
$queries = "SELECT * FROM status where project=3"
}
else if ($option == 'audit')
{
$queries = "SELECT * FROM status where project=4"
}
else if ($option == 'sggaming')
{
$queries = "SELECT * FROM status where project=5"
}
else ($option == 'all')
{
$queries = "SELECT * FROM status"
}
//store query as var result
$queries=$query;
$result=#mysqli_query($con,"$query");
//echo var result in table format
echo "<table border='1'>
<tr>
<th>Project</th>
<th>Subject</th>
<th>Status</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['project'] . "</td>";
echo "<td>" . $row['subject'] . "</td>";
echo "<td>" . $row['entry'] . "</td>";
echo "</tr>";
}
echo "</table>";
//close mysql connection
mysqli_close($con);
?>
Thanks for any help in advance!
OK, so it looks like you haven't fully grasped the client/server model employed in web based systems (we were all there at the beginning).
Here's a quick rundown, and then we'll talk about where you're issue lies.
You open a browser and type in a URL, hit enter
Your browser sends a request to the server that hosts the URL you entered
The server parses the request and loads up the specific file that was requested. For our purposes, that means running the PHP file to ultimately generate an HTML and javascript output
It sends this HTML (and javascript) to the browser. No executable PHP is ever sent to the browser, it all stays on the server.
Your browser receives this HTML (and javascript) and displays it.
Your browser can execute any javascript on the page, but if it needs information that is not already in your page source, it has to request it from the server. It can do this one of two ways: a) you can send a whole new request to the server, with the correct parameters such that the information you want is included up front or b) you can run an ajax request to pull the information you need, and then insert it into your page
So, at first glance it looks like the breakdown is occurring between step 5 and 6, you've loaded up a whole page in the browser, and it needs more information from the server but you're never actually sending that request to the server. If you were to send that request to the server (by either adding a submit button to your form, or adding a form submit request to your displayProject() function), then you've got no way (currently) to insert that new information into your existing page.
So, there's two potential answers to your problem:
If you want to understand better how to write a PHP application because you intend to do more of this in the future:
... then you should rewrite these two separate files as one single file. (I've dropped your code in pretty much as-is, I haven't done any checking for errors)
<?php
//create connection variables
$host=`localhost`;
$user=`dashboard`;
$pw=`password`;
$db=`status`;
//create connection
$con=mysqli_connect("$host", "$user", "$pw", "$db");
//check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//take input from form and store as var queries
$option= $_POST['option'];
if ($option == 'sciplay')
{
$queries = "SELECT * FROM status where project=1"
}
else if ($option == 'oklahoma')
{
$queries = "SELECT * FROM status where project=2"
}
else if ($option == 'northdakota')
{
$queries = "SELECT * FROM status where project=3"
}
else if ($option == 'audit')
{
$queries = "SELECT * FROM status where project=4"
}
else if ($option == 'sggaming')
{
$queries = "SELECT * FROM status where project=5"
}
else ($option == 'all')
{
$queries = "SELECT * FROM status"
}
//store query as var result
$queries=$query;
$result=#mysqli_query($con,"$query");
//The actual echo of the table display was moved to the area of the page it actually needs to go
//close mysql connection
mysqli_close($con);
?>
<html>
<head>
<title>Status Dashboard</title>
</head>
<body style="background:#19245e url('images/fade.png')repeat-x;font-size:12px;font-family: Arial;line-height:18px;color:#FFFFFF;">
<script>
function displayProject(option)
{
var x;
if (option=='sciplay')
{
x="show Sciplay selected, show notes, status, etc..."
}
else if (option=='oklahoma')
{
x="show OK selected, show..."
}
else if (option=='northdakota')
{
x="show North Dakota selected, show..."
}
else if (option=='audit')
{
x="show Audit selected, show..."
}
else if (option=='sggaming')
{
x="show SG Gaming selected, show..."
}
else if (option=='all')
{
x="..."//(option=(1+2+3+4+5))
}
document.getElementById("demo").innerHTML=x;
}
</script>
<div align="center">
<TABLE BORDER="1">
<TR>
<TD><img src='images/header.png'/>
</TD>
</TR>
<TR>
<TD>
<TABLE BORDER="0" bgcolor="C0C0C0" align="left">
<TH>Projects
</TH>
<TR>
<TD>
<!--
SOME CHANGES HERE: The form action is now pointing
to this same file, so that when you submit your form,
it goes back to this same file.
Also, I gave your select tag a "name" attribute so
that when you submit it, it'll actually be accessible
in the $_POST['option'] variable
-->
<FORM action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<SELECT name="option" onload="displayProject(this.value);" onchange="displayProject(this.value);">
<OPTION VALUE='all'>ALL</OPTION>
<OPTION VALUE='sciplay'>Sciplay</OPTION>
<OPTION VALUE='oklahoma'>Oklahoma</OPTION>
<OPTION VALUE='northdakota'>North Dakota</OPTION>
<OPTION VALUE='audit'>Audit SSAE16</OPTION>
<OPTION VALUE='sggaming'>SG Gaming</OPTION>
</SELECT>
<input type="submit" value="Reload Form">
</FORM>
</TD>
</TR>
</TABLE>
</TD>
</TR>
<TR>
<TD>
<!-- a <p> tag can't technically hold a <table> tag, but one thing at a time here -->
<p id="demo">
<?php
// I'm just lifting your structure out and placing it here for clarity purposes.
// really, you can just write these tags out in HTML directly,
// not go into PHP and echo them
echo "<table border='1'>
<tr>
<th>Project</th>
<th>Subject</th>
<th>Status</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['project'] . "</td>";
echo "<td>" . $row['subject'] . "</td>";
echo "<td>" . $row['entry'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</p>
</TD>
</TR>
</TABLE>
</div>
</body>
... so, what's going on here is that I've changed it up so that the data is being built and used, all in the same file. Your page now doesn't need to request new information, it's all right there, and if you want to change the form, then you submit and it requests the whole page again, now with the new information.
That's all well and good, but may not be exactly how you want your page to work. That said, you should understand how that process functions because any PHP application of even basic complexity will need to work in that way at least in part.
Now...
If you just want this page to function the way it appears you -want- it to function, i.e. you build your page, then request new information to update your page on form request:
... then we can get that done. Again, I haven't done any checking for errors. First things first, though, put this in your <head> tags:
<head>
<title>Status Dashboard</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
... we're going to be using jquery, just because in our case here, it let's us just worry about running the ajax request rather than bother setting up all of the necessary ins and outs. Then you want to add this to your displayProject function (just before the closing } ):
$.ajax({
url: 'getprojectstatus.php',
type: 'post',
data: 'option='+option,
success: function(data) {
$('#demo').html(data);
}
});
... all that's going on there is that you're sending your "option" selection to getprojectstatus.php, that file is generating your HTML output for your table, and then once it's received, it runs "success", which just inserts the data directly into the element with the "demo" id attribute. You should consider changing that to a <div>, at minimum, as the <p> might cause headaches.
I am not sure if I understand the problem correctly, but this might work for you:
<FORM action="getprojectstatus.php" method="post">
<SELECT onload="displayProject(this.value);" onchange="displayProject(this.value);">
<OPTION VALUE='none'>ALL</OPTION>
<OPTION VALUE='1'>Sciplay</OPTION>
<OPTION VALUE='2'>Oklahoma</OPTION>
<OPTION VALUE='3'>North Dakota</OPTION>
<OPTION VALUE='4'>Audit SSAE16</OPTION>
<OPTION VALUE='5'>SG Gaming</OPTION>
</SELECT>
</FORM>
And then in your PHP file:
$option= $_POST['option'];
$queries = "SELECT * FROM status"
if ($option != 'none'){
$queries = "SELECT * FROM status where project=".$option
}
I would also recommend researching some PHP Frameworks, maybe CodeIgniter and learning MVC patterns.

Display result in dropdown and select to perform query in php mysql

I have a database named Data which has a table in which their are different names of products their id and prices, i want to make a web page using php so that i can edit,add and save the items from the web page to the DB and search the names accordingly.
<html>
<head>
<title>Products store</title>
</head>
<body>
<p style="font-size:20px" align="center"> <b>Product Database Editor</b> </p>
<p>
<form method="post">
Enter Product Name: <input type="text" name="pname" id="pname" size="70">
<input type="submit">
</p>
<form method="post">
<select id="opt" name="opt">
<?php
$pname = $_REQUEST['pname'];
// $pname= mysql_real_escape_string($_POST['pname']);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Dataentry", $con);
$result = mysql_query("SELECT * FROM products where name like '%$pname%'");
$result_rows = mysql_num_rows($result);
if($pname==NULL)
{
echo "Please enter a product name!";
}
else if($result_rows==0)
{
echo "Product Name does not exist!";
}
else
{
while($row = mysql_fetch_array($result))
{
$name = $row['name'];
echo "<option value='$name_selected'>$name</option>";
//echo ("<option value = '" . $row['name'] . "'>" . $row['id'] . "</option>");
echo $name_selected;
echo "<br />";
}
}
mysql_close($con);
?>
</select>
</form>
</body>
</html>
when i run this code i get the names list in the dropdown but after i select any name, nothing happens, how should i modify my code so that i can select any name from the dropdown and then be able to fetch the price of that particular name to edit it.
please help, coding will be much helpful.
Suppose you have a question like this in your dropdown menu.
Q - How many colors does the US flag has?
Now, from what I understand you want your choice from the drop down menu to appear instantly..
Well, here is a simple select form.
<form method="post">
<select id="opt" name="opt">
<option value="four">four</option>
<option value="five">five</option>
<option value="two">two</option>
<option value="million">million</option>
</select>​
And, the JS code:
$(document).ready(function() {
$("#opt").change(function() {
alert($(this).val());
});
});​
Now, click her a DEMO with jsFiddle to show you, how it works.
You can copy/paste the codes and include them in your site, this is a simple code, but you if you small knowledge of Javascript you can manipulate the data the way you need it to appear. .
To get a value of an input (this case, from a dropdown) on the fly, you need to use client-side scripting language javascript (or jquery) and use ajax to sent it to server-side, where the code is in PHP.

Dropdown List Value From SQL in PHP

I want to do this function in php. i have two fields, one is text box and an
other one is drop down list. Drop down list contains values from sql. When one of the value is selected from the drop down list i want the text box to be filled according to the option which is selected.
Following is the drop down list code,
<td>Test Group ID</td>
<td><select id="testgroupid" name="testgroupid" style="column-width:35">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH)){
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select></td>
According to the id,I want textbox to be filled, How can i do this ? Pls help friends.
<tr>
<td>Test Group Name</td>
<td><input type="text" name="testgroupname" id="zipsearch" value="<?php echo $testgroupname; ?> "></td>
</tr>
If you want your textbox to be filled immediately after the dropdown selection changes, the simplest way is to use javascript:
<td><select id="testgroupid" name="testgroupid" style="column-width:35"
onchange='document.getElementsByName("testgroupname")[0].value =
document.getElementById("testgroupid").options[e.selectedIndex].value;'>
You need JavaScript for that. Use jQuery (or your favorite library) and bind an event listener to the combobox.
Example with jQuery:
$("#myCombo").change(function(e){
$("myTextField").val( $("#myCombo").val() );
});
I have one suggestion which involves jQuery. I do not know if you are using this library, but I am posting it anyway :)
<script type="text/javascript">
$(function() {
$("#testgroupid").change(function{
$("#zipsearch").text($(this option:selected).val();
});
});
</script>
On change event on the dropbown-box, this function fires, and sets the zipsearch-input accordingly.
I am not sure where $testgroupname comes from but I take it you would like to get that value upon selection in the dropdown. If you don´t have the value available on the client you have to retrieve it from the server somehow.
You can´t use PHP to fill the text box since you do not send your posts when an options is selected in the dropdown. There are many alternatives on how to solve this. I would personally use Ajax to fill the textbox without posting to server.
Good place to start:
http://buffernow.com/2012/08/cascading-dropdown-ajax/
html
<select id="testgroupid" name="testgroupid"
style="column-width:35" onChange=filltext();>
javascript
function filltext()
{
var e = document.getElementById("testgroupid");
var group = e.options[e.selectedIndex].text;
document.getElementById("zipsearch").value= group ;
}
your php code is wrong here
<option value="<?=$res['Id'];?>"><?=`$res['Id']`;?></option>
change to
<option value="<?=$res['Id'];?>"><?=$res['GROUP_NAME'];?></option>
Try like this
<script>
function selecteditem(selectedval)
{
jQuery.post("<?php echo JURI::root().'test.php'?>", { id: selectedval },
function(data) {
jQuery('.zipsearch').val(data);
});
}
</script>
//test.php on the root
<?php
$val=$_POST['id'];
//do what you want with $val
//and say final output is in variable $result than echo it
echo $result;
?>
<!--html code here-->
<select id="testgroupid" name="testgroupid" style="column-width:35" onclick="selecteditem(this.value);">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH))
{
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select>
<input type="text" name="testgroupname" id="zipsearch" class="zipsearch" value="<?php echo $testgroupname; ?> ">
<?php
// Assume $db is a PDO object
$dbh = new PDO('mysql:host=localhost;dbname=populatedropdown', "root", "");
$query = $dbh->query("select * from position"); // Run your query
echo '<form action="populate.php" method="get" name="send3">';
echo '<select name="populate">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';// Close your drop down box
echo '</form>';
?>
<script language="JavaScript">
function send_input1(){
document.send1.input4.value = document.send3.populate.value;
}
</script>
<form name="send1" action=javascript:send_input1()>
<p><input type=submit value=Enter>
</p><input size=30 name="input4">
</form>

Update MySQL using ID from drop-down-menu

I would like some help with my code. I've already searched answered questions on this site but haven't found anything that works unfortunately. I'm doing a website where you can write, save, delete and update notes. Now I'm trying to fix an update button were you can change a posted note using its unique ID. The update button is on a separate page from the notes, and you choose the ID of posted notes using using a drop-down menu showing the existing IDs in my database table. You choose it, write a new note and then click update.
This is my current code:
<li id="id_number"><label>ID number: <select name="id_number">
<option value =" ">Select number</option>
<?php $query = "SELECT * FROM notes";
$result2 = mysql_query($query);
while ($row = mysql_fetch_array($result2)) {
$id = $row ['id'];
$select = "";
if ($id == $idID2) {
$select = "selected" ;
}
?><option <?php print $select ?> value="<?php print $id; ?>"><?php print "$id";
?></option><?php
}
?>
</select>
</label></li>
<li id="note">New note:</li>
<li id="note"> <textarea rows="10" cols="30" name="note" value="<?php print $note;?>"/></textarea></li>
<li id="send"><input type="submit" name="submit" value="Update!"/></li>
</ul>
</form>
<?php
$id= $_POST ['id'];
$subject= $_POST ['subject'];
$note= $_POST ['note'];
?>
<?php
if (isset($_POST['submit'])) { //validates the data
$error="0";
if ( $note == "" ) {
$error++;
$wrong .= "<p> You forgot to write a new note.</p>";
}
if ($error > 0) {
print "<p><strong>You have made these errors:</strong></p>";
?>
<?php print $wrong; ?>
<?php
}
//if no errors
else {
$note = mysql_real_escape_string($note);
$note = htmlspecialchars($note);
$id = mysql_real_escape_string($id);
$id = htmlspecialchars($id);
$date = date("j/n, Y, H:i");
$query = ("UPDATE notes SET note='$note' WHERE id='$id'");
$result = mysql_query($query) or die (mysql_error());
if ($result) {
print "<p>Note updated!</p>";
}
}
}
?>
When choosing an existing ID and change the note and clicking update it says "Note updated" but the note in the database remains the same.
What am i doing wrong?
$id = $_POST['id']
should be
$id = $_POST['id_number']
As far as I can tell, you aren't referring to any input with name "id".
Instead of answering "what am I doing wrong?" I'm going to answer "How can I do this right?"
Your interface is set up in a fashion that is not intuitive. The dropdown should contain information about the notes (the ID is sufficient here), and when the user selects a note from the dropdown, your text input should be populated with what's already there. If no note ID is selected from the dropdown and the user clicks "update", the system should insert a new note record (if the text area has content).
So, how do we do this? First let's set up our form:
<form action="" method="post">
<select id="noteIds" name="noteId">
<option value=''>Select a Note</option>
<option value='1'>1</option>
<option value='2'>2</option>
.
.
.
</select> <br />
<textarea name="noteContents" id="noteContents"></textarea><br />
<input type="submit" value="Update" />
</form>
Now that we have our form set up we can control the behavior of the elements using jQuery:
<script language="javascript" type="text/javascript">
$("#noteIds").on('change', function() {
$.post("getNoteInfo.php", {
noteId: $(this).val()
}, function(data) {
$("#noteContents").html(data);
}
);
});
</script>
The above code will set the output of geNoteInfo.php to the contents of your textarea.
Next let's work on getNoteInfo.php (in pseudo-code).
<?php
$noteId = $_POST['noteId'];
$noteText = // retrieve note text from database where note ID = $noteId
echo $noteText;
Now, when the user clicks Update, check to see that an ID is selected. If the ID was selected, update that row. If no ID has been selected, insert a new row IF there is text in the textarea.
NOTE: You should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this SO article.

Categories