Passing dropdown data which is gatherd from a mysql table - php

I need a script that loads data form mysql and show on a drop down list. From there, I need to pass the selected data to another page.
I have done the first step. I am now able to load data from mysql table and to show them on a drop down menu. The exact is given bellow.
<?php
include("config.php");
$result= mysql_query("SELECT folder_name FROM folders");
echo '<select name="directory">'; // Open your drop down box
while ($row = mysql_fetch_array($result)) {
//echo "<option>" . $row['folder_name'] . "</option>";
echo '<option value="'.$row['folder_name'].'">'.$row['folder_name'].'</option>';
}
echo '</select>';// Close your drop down box
?>
Now I need help to pass the selected data to another page. Any suggestion please?

Let me consider the form is posted to page2.php from page1.php
page1.php
<form method="post" action="page2.php">
//your dropdown code here
<?php
include("config.php");
$result= mysql_query("SELECT folder_name FROM folders");
$str = '';
$str .= '<select name="directory">'; // Open your drop down box
while ($row = mysql_fetch_array($result)) {
$str .= '<option value="'.$row['folder_name'].'">'.$row['folder_name'].'</option>';
}
$str .= '</select>';// Close your drop down box
echo $str;
?>
<input type="submit" value="submit" />
</form>
in page2.php you can access the dropdown selected value as
$selVal = '';
if(isset($_POST['directory']))
{
$selVal = $_POST['directory'];
}

create a javascript function to handle the redirect with the folder name data:
function changePage(folder){
window.location.href= 'http://www.yourdomain.com/page2.php?folder=' + folder;
}
onchange option, trigger changePage javascript function with folder name as input:
include("config.php");
$result= mysql_query("SELECT folder_name FROM folders");
echo '<select name="directory">'; // Open your drop down box
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row['folder_name'].'" onchange="changePage(\''.$row['folder_name'].'\')">'.$row['folder_name'].'</option>';
}
echo '</select>';// Close your drop down box
page2.php
$folder_name = strip_tags($_GET['folder']);

Related

Print selected value from dynamic dropdown php mysql

I have the below code where I can get dynamic value into drop down list from mysql db but i can't print selected value when i click on submit button.
can anyone help me urgntly ?
<?php
include("includes/config.inc.php");
$query = "SELECT * FROM category";
$result = mysql_query ($query);
echo "<select class='turnintodropdown' name='CategoryID' ><option value=''>All</option>";
while($r = mysql_fetch_array($result)) {
echo "<option value=".$r['CategoryID'].">".$r['CategoryName']."</option>";
}
echo "</select>";
if (isset($_POST['submit'])) {
$selected_val = $_POST['CategoryID']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
?>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
If you want to preselect the selected value of the then you can use the following code. Also check your form method attrivute to see if it set to post (note that mysql_* functions are deprecated, it's better to use PDO using prepared statements).
while($r = mysql_fetch_array($result)) {
if (!empty($_POST['CategoryID']) && $_POST['CategoryID'] == $r['CategoryID']) {
$selected = 'selected="selected"';
} else {
$selected = '';
}
echo "<option ".$selected." value=".$r['CategoryID'].">".$r['CategoryName']."</option>";
}
from above:
echo "you have selected :" . $selected_val;
from what you are echoing, based on what I'm exp[laining], it echos the ID, not the name of the category.

How to put check-boxes next to data displayed from the database - PHP, SQL

I am displaying some data from my database, and I wnat to be able to put checkboxes next to each record displayed.
Afther that I want the user to be able to submit their selection and that will then delete the selected records.
I googled a lot of things, but could not make anything work. I'm looking for smething simple.
Here is my code:
<?php
//include('conn.php');
$con=mysqli_connect();
session_start();
if (!isset($_SESSION['ID'])){
header('location:login.php');
}
//
?>
<?php
if (!$link = mysql_connect()) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db()) {
echo 'Could not select database';
exit;
}
$villageId = $_GET['village'];
$ID = $_SESSION['ID'];
$sql ="SELECT *
FROM favourites
INNER JOIN attractions ON favourites.AttractionID = attractions.AttractionID
INNER JOIN customer ON favourites.ID = customer.ID
WHERE favourites.ID = '$ID' ";
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['Name'] ;
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Can anyone give me some suggestions?
Thanks.
Simple add checkbox near data output:
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' /> ".$row['Name'];
}
As I understand you need this:
Output some rows data - checkbox
User will select some checkboxes and data, connected with that checkboxes will be deleted from the database.
Delete deleted data from the page.
How to achieve this?
You need html code below to ahieve what you want (+ you need some javascript, I will tell about it later):
<form id='myForm'>
<div id='1'>
<input type='checkbox' name='data[]' value='1' />Row 1</div>
<div id='2'>
<input type='checkbox' name='data[]' value='2' />Row 1</div>
<div id='3'>
<input type='checkbox' name='data[]' value='3' />Row 1</div>
</form>
Look the example of that code + serialize form on link onclick handler here.
Generate same output in PHP:
// execute query
echo "<form id='myForm'>";
while ($row = mysql_fetch_assoc($result)) {
echo "<div id='".$row['id']."'><input type='checkbox' value='".$row['id']."' /> ".$row['Name']." </div>";
}
echo "<a href='#' id='delete'>Delete</a>";
echo "</form>";
So, now we made 1st item of our list and half of 2nd (serialize form).
How to achieve another half of 2nd item. We have to create php script where we will delete rows from the database.
deleteScript.php script:
// connect to the base
foreach($id in $_POST['data']) {
$query = "delete from `favourites` where `id` = ".$id;
// execute your query
}
Script ready. Now you have to send request from our page to this script. Use ajax request for it:
$("#delete").on('click', function () {
var data = $("#myForm").serialize();
if(data != '') {
$.ajax({
url: "deleteScript.php",
data: data
});
}
else
{
alert("select some checkboxes");
}
});
This javascript code works with previous html code
Example here.
Now, 1st and 2nd items of our list done.
Let's delete deleted items from our page immidiately (3rd item of todo list):
$("input:checkbox:checked").each(function()
{
var id = $(this).val();
$("div#"+id).remove();
});
You can test this code here
That example was created to show you, that my approach works. But! You have to remove div's only if request had been sent successfully. So you have to edit $.ajax success handler. Check this fiddle for it.
So, now we made all items from our list.
Final example here: http://jsfiddle.net/575VS/18/
You have to copy past it just to your files :)
Hope, this will help.
Note, that you can get ajax-request response.
$.ajax({
//some properties
success: function(data) {
//response will be in data variable
}
});
If you want to redirect page right after deleting selected rows in database use this code:
if(data != '') {
$.ajax({
url: "deleteScript.php",
data: data,
success: function() {
window.location.replace("new link here");
}
});
}
Just to expand on Sharikov's answer: You need to place the checkbox in the loop as he described, but if you want to be able to pass that info to another script, that works on the user input you need several more things:
echo "<form action='receiver.php' method='post'>";
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' name='checkedBoxes[]'/> ".$row['Name'];
}
echo "<input type='submit' value='process'>";
echo "</form>";
Then on receiver.php:
foreach($_POST['checkedBoxes'] as $box){
$id = $box;
//THEN DO SOMETHING TO EACH ID
}
If you also want to see which boxes were unchecked, then things get a little more complicated because POST and GET will only pass the values of checked check-boxes. and there are several ways I can think of to do this. One way would be to pass an array of the all ids displayed via a $_SESSION variable to the next script:
session_start();
$ids = new Array();
echo "<form action='receiver.php' method='post'>";
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' name='checkedBoxes[]'/> ".$row['Name'];
array_push($ids, $row['id'];
}
$_SESSION['ids'] = $ids;
echo "<input type='submit' value='process'>";
echo "</form>";
And then on receiver.php you can reference that array with $_SESSION['ids'] and compare it to the values that were checked. Just make sure you place session_start(); in your code to be able to see the variable!
Good Luck!

How can I get the selected value from a drop down list

I am trying to use a dynamically generated dropdown list to populate a table. I have a drop down list that is generated from my database (it grabs all the years available for a specific player). I want to be able to select a year from the dropdown and have it update my table. I have the dropdown being generated, but I am not able to get the selected value from the dropdown. I have code below that I found here, but it doesn't seem to work. Here is the code I have so far:
<input name="update" type="submit" value="Update" />
</form>
<p></p>
<form action="player_login.html">
<input type="submit" value="Logout" />
</form>
</div>
<div style="float: left">
<p></p>
<h1>Player Stats</h1>
<table width="300" border="1" cellpadding="2" cellspacing="2">
<?php
// get "id" field from player table
$login_id = $_COOKIE["DB"];
$id = "select id from player where login_id='$login_id';";
$result1=mysql_query($id) or die('Select1 Query failed: ' . mysql_error());
$row = mysql_fetch_array($result1);
// create a dropdown from stats table in db
echo "--Select Year--";
$years_query = "select year from stats where player_id='$row[id]';";
$years = mysql_query($years_query, $connect);
// fill array with db info
$var = array();
while ($row2 = mysql_fetch_array($years))
{
$var[] = $row2['year'];
}
// create dropdown
echo'<select name="years" id="years">';
// For each value of the array assign variable name "city"
foreach($var as $year)
{
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select>';
// get selected option from dropdown
$selected_key = $_POST['years'];
$selected_val = $var[$_POST['years']];
echo "<p></p>selected key: " . $selected_val; // this wont print anything???
$search_query="select * from stats where player_id='$row[id]' and year=2013;";
$result=mysql_query($search_query) or die('Select2 Query failed: ' . mysql_error());
$num_cols = mysql_num_fields($result);
$line = mysql_fetch_row($result);
// create table with results
echo "<tr>";
echo "<td>Year</td>";
$j=1;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Total Points</td>";
$j=2;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>PPG</td>";
$j=3;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
?>
</table>
</div>
I see that you use $_POST and since form is not submitted and thus data of $_POST is not set. Best available option I have used to catch the event and send the AJAX Query fetch results and update it.
I have done this with the help of J Query as under
$('#years').change(function() {
$.ajax({
//request of AJAX
type : 'POST',
url : 'players_data.php',
dataType : 'json',
data: {
//Data with $_POST request
years : $('#years').val();
},
success: function(data){
//Things to be done with returned data
}
}};
Create a new file players_data.php and there you write the code for fetching data from the db as:
// get selected option from dropdown
$selected_key = $_POST['years'];
$selected_val = $var[$_POST['years']];
echo "<p></p>selected key: " . $selected_val; // this wont print anything???
$search_query="select * from stats where player_id='$row[id]' and year=2013;";
$result=mysql_query($search_query);
$num_cols = mysql_num_fields($result);
$line = mysql_fetch_row($result);
$return['year']=$line;
echo json_encode($return);
I see that you are using $_POST, and why do you don't use a form?
//This is for get the form
echo '<script type="text/javascript">
//<![CDATA[
function get_form( element )
{
while( element )
{
element = element.parentNode
if( element.tagName.toLowerCase() == "form" )
{
return element
}
}
return 0; //error: no form found in ancestors
}
//]]>
</script>';
//create a form
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">';
// create dropdown; onchange will send the form when selected index changes...
echo '<select name="years" id="years" onchange="get_form(this).submit(); return false;">';
// For each value of the array assign variable name "city"
foreach($var as $year)
{
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select></form>';
And that's all! :D
I'm seeing too that you are using an unique form for update all the page... It's isn't work, because you only have a submit button and no more element in the form, please read that: http://www.w3schools.com/tags/tag_form.asp
From your code i can see that u want to get the value from the select box and immediately populate the table and display the results..use jquery to get the value of selected object and assign the javascript variable to a php variable. and insert into the db..
<script type="text/javascript">
$( "#years" ).change(function() {
var value=document.getElementById("years").value;
alert(value);
</script>
assign the variable to php and execute you php query.
<?php
$data = "<script>document.write(value)</script>";
//execute your query here..
?>
Also have a look at ajax..it does that so well...

Inserting PHP in an HTML form to populate a selection

I have a HTML form that has a selection drop down. I would like to populate the drop down from my MySQL DB. The HTML form already has some java scripts to handle datepicker, and current date on one of the fields in the form.
I can code the form for the selection manually, but would like it to come from MySQL. the php I am using I put in it's own file name.php to make sure it worked correctly. I added some echo statements in the php to build the form, and the selection, and then populate the selection, and close it. this worked just fine as a standalone php.
When I append the php in the form under the selection definition, it does not populate the selection at all, it is left blank/empty. If I add some echo statments to output info in the format of a selection option, the first echo never shows up, and the subsequent echos show up, but any variable show up as the variable name.
<form id="form1" name="form1" method="post" action="/db_log.php">
Field:<select name="id">
<?php
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DB_CONNECT();
$query="SELECT id, name FROM file order by name";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name =$row['name'];
echo "<option value=\"$id\"> $name </option>";
}
?>
</select><br />
</form>
the above yealds an empty select dropdown.
But this works great as a PHP file.
<?php
echo "<form id=\"form1\" name=\"form1\" method=\"post\" action=\"/db_log.php\">";
echo "Select:<select name=\"id\">";
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DB_CONNECT();
$result=mysql_query("SELECT id, name FROM file order by name");
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name =$row['name'];
echo "<option value=\"$id\"> $name </option>";
}
echo "</select><br />";
echo "</form>";
?>
If I add a echo to the HTML form one like a test echo before any other echo, it is ignored.
<form id="form1" name="form1" method="post" action="/db_log.php">
Field:<select name="id">
<?php
echo "<option value=\"1\"> Test-name </option>";
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DB_CONNECT();
$query="SELECT id, name FROM file order by name";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name =$row['name'];
echo "<option value=\"$id\"> $name </option>";
}
?>
</select><br />
</form>
the only thing that shows up from this is the option to select $name
Based on this question and the previous questions and the comments you've gotten and made I'm going to guess that you're trying to run php from a .html file. You need to save your code (including the html) in a .php file for it to work.
A have a combo box that feeds from my mysql database.
I goes like this:
<tr>
<td>Emergency service</td>
<td><?php
$nombreEmergencia;
$idEmergencia;
$sql4 = "SELECT `idEmergencias`, `nombre` FROM `emergencias` WHERE 1";
$iterador = $conn->consulta($sql4);
echo '<select name="idEmergencia" id="idEmergencia" style="width:228px">
<option value="-1" selected>(please select:)</option>';
while($iterador->hayElemento()){
$nombreEmergencia = $iterador->getElemento("nombre");
$idEmergencia = $iterador->getElemento("idEmergencias");
echo '<option value="'.$idEmergencia.'">'.utf8_encode($nombreEmergencia).'</option>';
}
echo '</select>'; ?></td>
</tr>
as you can see you have to use an "iterator" variable with a function that checks the database for more elements and brings 'em.
That auxiliary function looks like this:
<?php
class Iterador{
private $ultimoDato;
private $id;
public function __construct($id){
$this->id = $id;
}
public function hayElemento(){
$dato = mysql_fetch_array($this->id);
$this->ultimoDato = $dato;
return !empty($dato);
}
public function getElemento($columnas){
return $this->ultimoDato[$columnas];
}
public function inicializar(){
$dato = mysql_fetch_array($this->id);
$this->ultimoDato = $dato;
}
public function hay(){
return !empty($this->ultimoDato);
}
public function siguiente(){
$dato=mysql_fetch_array($this->id);
$this->ultimoDato=$dato;
}
}
?>
hope this helps!!

Php drop down menu

i am using following code to insert data into mysql database
<?php
$refselect = $_POST['refselect'];
$refname = $_POST['refname'];
$refemail = $_POST['refemail'];
$refcnt = $_POST['refcnt'];
$refdes = $_POST['refdes'];
$referror = $cberror = "<h1>Data not Added</h1><br/><br/><h3>Please Follow The Instructions</h3>";
$urefdb = "INSERT INTO refdb(reftype,refname,refemail,refcnt,refdes) VALUES ('$refselect','$refname','$refemail','$refcnt','$refdes');";
include_once("db.php");
if ($refselect == "Select Type") die ("$referror");
if (empty ($refname)) die ("$referror");
if (mysql_query("$urefdb"))
{
echo "<h3>One Record Updated Successfully with the following Details </h3><br/>";
echo "Reference Type =$refselect <br/><br/>";
echo "Reference Name = $refname <br/><br/>";
echo "Reference E-Mail = $refemail <br/><br/>";
echo "Reference Description = $refdes <br/><br/>";
}
else
{
echo mysql_error();
}
?>
"refselect" data is coming from a drop down menu at the page now i want that as i add data through this form another form located at another page pic "refname" from database as i update "refdb" that drop down menu pick data accordingly
what to do now ?
You have to fill the dropdown menu on that another page using MySQL select like:
$request = mysql_query("SELECT refselect FROM refdb");
then iterate through all the results to fill your combobox:
echo "<SELECT>";
while ($drow = mysql_fetch_assoc($request))
{
echo "<OPTION>" . $drow['refselect'] . "</OPTION>";
}
echo "</SELECT>";
Or something like this

Categories