perform mysql select statement when a dropdown menu item is selected - php

I am developing a web application and i am stuck with a problem.
i have two drop-down list, one is dynamically populated from my db, while the the other is static html.
When a user selects an item form the dynamic drop-down and select an item from the static html drop-down, and clicks submit on the form, I would like the dynamic selected list item to print out the entire selected row in the db.
here is my code sample
if ($contactc =="Yes"){
$result = mysql_query("SELECT * FROM company_details where comid = '$selectsector'");
while ($row = mysql_fetch_array($result)){
echo $row["fname"]." ".$row["comname"]."<br/>";
}
}

maybe this is what you wanted, though you will have to use JQuery
HTML
<form id="when_user_clicks_submit_button">
<input class="data_to_send" type="text" value="MySQL Selection data"></input>
<input type="submit" value="Submit"></input>
</form>
JavaScript|JQuery for Ajax Request:
document.getElementById('when_user_clicks_submit_button').onsubmit = function() {
$.ajax({
type: "POST",
url: "php_code_script.php",//php script location
data: { "data_from_form": data_to_send }, //data to send in JSON format
success: function(data) { //callback if the script execution is successful
$('<p>' + data + '</p>').appendTo('body');//this returns the selected information from the MySQL database and inserts it somewhere, make sure to echo or print the selected data inside the php script.
}
)}
};
PHP
if($_POST['data_from_form']) {
if ($contactc =="Yes"){
$selectsector = $_POST['data_from_form']; //gets the sended data from the form page to use for selection in the MySQL database
$result = mysqli_query("SELECT * FROM company_details where comid = '$selectsector'");
while ($row = mysqli_fetch_array($result)){
echo $row["fname"]." ".$row["comname"]."<br/>";
}
}
}
Maybe this is sort of what you wanted, you basically send the information you want to use to select from the database, the php script then handles it and echoes the selected information from the database, that data then returns to the form page where it becomes the value pf an DOM Element(HTML tag). This is just to give an example of what you maybe want, I didn't think about security or anything(I don't know much about it yet). Note I also changed the mysql to mysqli to make it more compatible with newer versions of PHP because mysql is no longer supported in newer versions or for the future.

Related

How to retrieve data from mysql php and show in table from dropdown

Hey guys i am a newbie to php.What problem i am facing is i have created a dropdown which is populated from the data from database using this code.This is working fine for me and it is populating dropdown too
include('connect.php');
$query="select * from faculty";
$result=mysql_query($query);
while($row = mysql_fetch_assoc($result))
{$dropdown.="\r\n<option value='{$row['Designation']}'>{$row['Designation']} </option>";}
echo "<select>".$dropdown."</select>";
Solution i want is,when a user selects a value from dropdown,result should be retrieved from database and should be displayed in table.Please help me guys
You have to basically :
1) Perform a form sending to some server side script(PHP in your case) when there is a change in the dropdown selection (use onchange event for the dropdown) and fetch the values from the db ,
2) Tell the server side script to spit out an html string which contains the table containing the desired information.3) 3) Output the string on your page.
This will do a page refresh.
If you donot want to have a page refresh, resort to using Ajax.
P.S. I recommend using some framework such as jQuery in case you need to use Ajax
What you have to do is something like this:
In your Html:
<select onchange="fetchContent()">
<option id="1_Designation">abcd</option>
<option id="2_Designation">1234</option>
<option id="3_Designation">lkjh</option>
</select>
In your javascript:
fetchContent()
{
id = $(this).id;
$.ajax({
type: "POST",
url: "/path/content.php?id="+id,
success: function(response) {
$("#tableRow").html(response);
}
});
}
In content.php you will have to get the value of id and then do the necessary data retrieval and then return the data.
$id = $_POST['id'];
//retrieve the data to $data
echo $data;

How to build a dynamic query based on dropdown option?

EDITED:
SQL
$valuefromjs = $_REQUEST['var'];
$result6 = "SELECT DISTINCT $valuefromjs FROM persons ORDER BY $valuefromjs ASC";
$result7 = mysql_query($result6);
$num = mysql_num_rows($result7);
$dataRanges[0] = array('dataRanges');
for ($i=1; $i<($num+1); $i++)
{
$dataRanges[$i] = array( (int) mysql_result($result7, $i-1) );
}
echo json_encode($dataRanges);
HTML
<select id="combo2" class="combo" data-index="2"></select>
jQuery
$('#1combo').on('change', function () {
var jsonVar = $.ajax({
url : "visits/comboquery.php?var="+$(this).val(),
dataType: "json",
async: false,
success: function(response) {
}
}).responseText;
for (var i=1; i<objVar.length;i++)
{
$('#combo2').html("<option value="+objVar[i]+">"+objVar[i]+"</option>");
}
});
QUESTION:
I have an array with query results. Now i need that results be the combo2 options, what is wrong?
To my understanding the choice from combo1 will define which query to run for building combo2.
The issue: your PHP for building the combo2 is parsed at the server side i.e. the PHP code is always finished executing by the time the page reaches the user's browser and your javascript begins to execute.
If you have a finite set of possible queries that can generate the seconds combo (which should be the case since combo1 has a finite number of options), you can create all of them, each with a different id, and maintain them hidden (css "display: none").
<select id="firstCombo2" class="combo2">
...
</select>
<select id="secondCombo2" class="combo2">
...
</select>
etc.
Now, when the user makes a selection from combo1, you can decide which one of the hidden combo2's you are going to display (css "display: block").
$('select#combo1).on("change", function(){
$('select.combo2').css('display','none'); //hide all combo2's
if($(this).val()=='Opt1'){
$('select#firstCombo2').css('display','block');
}else if($(this).val()=='Opt2'){
$('select#secondCombo2').css('display','block');
}
}
You should use AJAX in order to solve your problem.
on combo1 onChange call an AJAX call to your server and send selected value of combo1.
Then in your php code run query with value received from AJAX request and construct a new combo box with options in string and echo back that string. You can use that AJAX response to populate new combo2.

PHP jQuery dynamically populated SELECT

Have been looking around for a solution to this and have found some help on stack overflow but in most cases the examples I have found are not using arrays formed from a database query. Here is some code for what I am trying to achieve...
$stores = mysql_query("SELECT * FROM Stores");
$staff = mysql_query("SELECT * FROM Staff");
I would like to create two elements, one for stores and another for staff but I want to filter the staff based on the store client side. So if the user selects "Sydney" from the first dropdown, they are presented with only staff that work at the Sydney store in the second dropdown. Then if the user chooses "London" from the first dropdown, the Sydney staff are replaced by the London staff and so on.
My server side scripting is done with PHP and I am able to create the two dropdowns with PHP. But I am stuck on the jQuery to remove the I don't want from the second dropdown.
I know this is possible, because I see it used all the time. I have seen lots of examples of how to manage this but none of the examples use data from the PHP array to insert the .
You need ajax.
When the user selects something in a dropdown, this fires an event that you can process. Inside of this process you take the value of the selection like jQuery('#id_dropdown').val(), and send this via ajax (I like using POST since you dont run into GET request size limits).
You process this on the server side with php, accessing to the database with the value selected and sent via ajax. When you have the right results for the second dropdown you can output it via echo.
Finally, when the response is returned to jQuery, you can insert all the options in the new dropdown.
JAVASCRIPT PART:
Bind event to the first dropdown
Get value of the option selected in the dropdown
Make ajax request
Here is some example code:
var parameters='value_selected='+value_dropdown;
jQuery.Post({
url: '/destiny_when_I_process',
data: parameters,
success: func_callback
});
//here you can imagine a pause, because PHP is processing the data you send by post
//....
//....
//this part is executed when php send the information
function func_callback(response_from_php){
jQuery('#second_dropdown').html(response_from_php);
}
PHP PART:
get value from POST
access database using this value
echo (send response). You send a chain of text (in HTML), really this is not very professional, but is OK for demonstration purposes. Professionals send JSON, since JSON is lighter-weight.
JAVASCRIPT PART (SECOND PART)
in the callback function, you receive the response data via the first parameter
Insert new data in the second dropdown (since the data is already HTML, you do not need to process it)
for the secondary drop down, yes, you'll need some ajax.
You can create a script that go fetch the result coresponding to the store and send back the option listm witch is inserted in the ooption.
Using jquery and php you'll need a few thing.
A php file to get the result and return the options. (let say getStaff.php)
<?php
//get the store id by post is it is set
if (isset($_POST['store->id']) $store_id = mysqli_real_escape_string($_POST['store_id']);
//get the data !! notice the WHERE caluse
$r = mysql_query("SELECT * FROM Staff" *WHERE store=''$store->is*);
//split the data in the array
$staffs=array();
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$staff->id=$assoc['id'];
$staff->name=$assoc['name'];
//and so on for each colum in your table.
array_push($staffs, $assoc);
}
//echo the result as option
foreach ($staffs as $staff) echo "<option value='$staff->id'>$staff->name</option>";
?>
In you first select, add
onchange="$.post('getStaff.php', {store_id:$(this).val()}, function (data){ $('#staff_select').html(data);});"
and add an id to your second select (staff_select) in this ecample.
As an explanation: When the 1st dropdown change, it send a request to getStaff.php with the store_id as a POST argument. The php sript get the syaff according to the store Id and bring back a list of option tags for your secondary select. Than jquery add the 'data' to your secondary select and VOilà!
Hope tih sis clear cause it's a bunch of little thing together that will make it work. Sorry if it's seems sloppy as an answer but it's really simple once you know it.
Spent the afternoon learning how to do this and it's working quite well. Posted the new code here for others....
Thanks to http://forum.codecall.net/topic/59341-php-sql-jquery-and-ajax-populate-select-boxes/ for the tutorial.
And thanks to everyone here.
PHP to build for the first :
function agency_select() {
include('../include/dbase.php');
$agencies = $pdo->query("SELECT * FROM agency WHERE Status='active' ORDER BY AgencyName");
$opt = '';
while ($age_array = $agencies->fetch(PDO::FETCH_ASSOC)) {
$opt .= '<option value="'.$age_array['AgencyId'].'">'.$age_array['AgencyId'].' - '.$age_array['AgencyName'].' - '.$age_array['AgencySuburb'].'</option>'."\n\t\t\t\t\t\t\t";
}
return $opt;
}
HTML for the two elements:
<label for="AgencyId">Client/Agency:</label>
<select class="uniform" id="AgencyId" name="AgencyId" style="width: 400px; overflow-x: hidden">
<?php echo agency_select(); ?>
</select>
<label for="Contact">Contact: </label>
<select class="uniform" id="Contact" name="Contact" style="width: 300px; overflow-x: hidden">
<option value="">----Select Client/Agency----</option>
</select>
AJAX file:
if(isset($_POST['AgencyId'])) {
include('../include/dbase.php');
$option = '<option value="">----Select Contact----</option>';
$query = $pdo->prepare("SELECT * FROM client WHERE AgencyId= ? AND Status='active' ORDER BY FirstName");
$result = $query->execute(array($_POST['AgencyId'])));
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$option .= '<option value="'.$row['id'].'">'.$row['FirstName'].' '.$row['LastName'].'</option>';
}
echo $option;
}
jQuery:
$(document).ready(function () {
update_contacts();
});
function update_contacts() {
$('#AgencyId').change(function() {
$('#Contact').fadeOut();
$('#loader').show();
$.post('../ajax/ajax_contact_select.php', {
AgencyId: $('#AgencyId').val()
}, function (response) {
setTimeout("finishajax('Contact', '"+escape(response)+"')", 400);
});
return false;
});
}
function finishajax(id,response) {
$('#loader').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
i'll try to help you as much as i can a explain it.
mysql_query, you sould use mysqli btw, mtsql being decrecated, return a result set.
This means you will have all the records from your query. You need to brak down your result into before you can work with it. This is done by using methids like mysql_fetch_assoc, mysql_fetch_row, etc. There something like fetch to array to but i don't master it so i will use fetch assoc, for this reply.
So once you have yoru result set, $stores & $staff in your case, you then call a while loop on your results to get th data as in:
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$stores->id=$assoc['id'];
$stores->name=$assoc['name'];
//and so on for each colum in your table.
array_push($stores, $assoc);
}
Then you can export it as you want.
in you case would be something like
foreach ($stores as $store) echo "<option value='$store->id'>$store->name</option>";
I storngly suggest you take alook at http://php.net/manual/en/function.mysql-fetch-array.php witch will do the same a fetch_assoc bu with an array with the columname as key.

Using one <form>'s selection to feed into another <form>?

From within php, I have a large html <form> filled out with lots rows of patient info from a postgres database. When a doctor double-clicks on a row, it sets a var in $_POST and invokes another php script to read up and display specific info about that row from the database. This all works.
But there are now so many rows of patient data that the doctors don't want to scroll and scroll to find the patient rows they're looking for, they want a patient prefilter <form> so that a click on an element in it will result in the large display filtered to just that patient's rows.
What's a basic approach to doing this? I'm a newb; I'm currently using html, php, and some javascript.
Make a second form with whatever options you'd like to filter on, this part will be specific to your data but you want something like
<form id="search-form">
<label>Name:</label><input type="text" name="patient-name"></input>
</form>
You'll need to build a query string (and make sure you use GET, because that will make things easier for you). This will require tweaking if you want to use radio buttons, or something similar, but here's the general idea:
function getSearchParameters () {
var form = document.getElementById('search-form');
var inputs = form.getElementsByTagName('input');
var result = '';
var i;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value) {
result += "&" + inputs[i].name + "=" + inputs[i].value;
}
}
return result;
}
In the onClick handler for your patient data links, you'll call this function and append its result to your query string:
element.onclick = function () {
var patientDataUrl = '/patients.php?param1=someValue';
patientDataUrl += getQueryParameters();
/* then do your ajax stuff as normal */
};
Then on the server side, within patients.php simply check for the presence of the search fields i.e.
if(isset($_GET['patient-name'])) {
$patient_name = mysql_real_escape_string($_GET['patient-name']);
$query = "SELECT * FROM `patients` WHERE `patient_name`='$patient_name';";
} else {
$query = "SELECT * FROM `patients`;";
}
(make sure you sanitize the string!)
I'd recommend considering a JS framework to make your life much easier (for instance, jQuery would allow you to send this via POST or easily serialize it into a GET query string via .serialize())

Combine JQuery/PHP to log clicks into database?

The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.
I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.
Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.
How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?
Below is the JQuery function.
$(document).ready(function() {
$('.accordionButton').click(function(e) {
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
$(this).next().slideDown(test_accordion);
// SEND CLICK ACTION TO LOG INTO THE DATABASE
alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
}
else {
$(this).removeClass('on');
$(this).next().slideUp('normal');
$(this).next().slideUp(test_accordion);
}
});
}
You can do something like this (untested):
Define a javascript variable to track the order of the clicks, outside your click function:
var order = 0;
Add this into your click function, at the bottom:
order++;
var sessionID = $("input[name='sessionID']").val(); // assuming you have sessionID as the value of a hidden input
var query = $("#query").text(); // if 'query' is the id of your searchbox
var pos = $(this).index() + 1; // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});
In your php script called "logClick.php" (in the same directory):
<?php
// GET AJAX POSTED DATA
$str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
$str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
$int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
$int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];
// CONNECT TO DATABASE
if ($str_sessionID && $str_query) {
require_once "dbconnect.php"; // include the commands used to connect to your database. Should define a variable $con as the mysql connection
// INSERT INTO MYSQL DATABASE TABLE CALLED 'click_logs'
$sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
$res = mysql_query($sql_query, $con);
if (!$res) die('Could not connect: ' . mysql_error());
else echo "Click was logged.";
}
else echo "No data found to log!";
?>
You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
function(result) {
$('#result').html(result); // display script output into a div with id='result'
// or just alert(result);
})
);
EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).
Example (put this in every results page):
<?php
$order = empty($_POST["order"]) ? $_POST["order"] : "0";
$html="<form id='form_session' action='' name='form_session' method='POST'>
<input type='hidden' name='order' value='$order'>
</form>\n";
echo $html;
?>
In your jQuery, just change var order = 0; to
var order = $("input[name='order']").val();
Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:
$("a.next_page").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("input[name='order']").val(order);
$("#form_session").attr('action', url).submit();
});
All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).
EDIT: If your pagination is as follows:
<div class='pagination'>
<ul><li><a href='page1.url'>1</a></li>
<li><a href='page2.url'>2</a></li>
</ul>
</div>
then just change this:
$("div.pagination a").click(function(event) {
etc.
This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.
In your search page you'll need to add an .ajax to create an AJAX request to your Script.
Everything you need to know about AJAX can be found here: http://api.jquery.com/jQuery.ajax/
In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.
Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.
A little example, on click:
$.post(
'count_click.php',
{ id: "someid" },
function(data) {
// data = everything the php-script prints out
});
Php:
if (isset($_POST['id'])) {
// add a click in the database with this id
}
Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):
http://api.jquery.com/jQuery.ajax/
In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
Something like:
$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston"
success: function(data){
alert('done');
});

Categories