How can I solve this mysql search query - php

I'm working on a chained select drop down that pulls data from the database to populate the category combobox while the subcategory combo box populates when an option from the category combobox is selected. The category dropdown box pulls data from database without any issue but I am having problems with getting the subcategorycombo box select data from database based on the 'id' of the option selected in the category combo box.Any help pls?below is my php code and the jquery code that display the data
<?php
include ('../storescripts/connection.php');
function ShowCategory(){
$sql = "SELECT * FROM category";
$res = mysql_query($sql) or die(mysql_error());
$category = '<option value="0">Choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value = "'.$row['category_id'].'"> '.$row['category_name']. ' </option>';
}
return $category;
}
function ShowSubCategory(){
if (!isset($_POST['id']))
{
//If not isset -> set with dumy value
$_POST['id'] = "";
}
$sql1 = "SELECT * FROM subcategory WHERE category_id = '$_POST[id]'";
$res1 = mysql_query($sql1) or die(mysql_error());
$subcategory = '<option value="0"> Choose...</option>';
while($row = mysql_fetch_array($res1)){
$subcategory .= '<option value="'.$row['subcategory_id'].'"> '.$row['subcategory_name'].' </option>';
}
return $subcategory;
}
?>
//jquery code
<script type="text/javascript">
$(document).ready(function() {
$("select#category").change(function(){
var id = $("select#category option:selected").attr('value');
$.post("select_subcat.php", {id:id}, function(data){
$("select#subcategory").html(data);
});
});
});
</script>

Try to narrow down what could be the problem. Have PHP print out the SQL statements to the page when you make a selection.
Then you can feed that exact statement into MySQL (through command line or via phpmyadmin) and see if you get the results you want. If you do, then the problem is later down the line. What do you see?
I will agree with earlier poster - if the $_POST id is not set, you fill it with ""? That probably won't get any results.
One last note: at very least use mysql_real_escape_string() before you ever touch any $_POST or $_GET variables. You are opening your site up to a number of SQL injection attacks otherwise.

Related

How can I best put a drop down list or select tag inside a html table - And then update a row if changed to mysql? complicated

I have a database containing a name and a status column. It contains data displayed in a table (obvious!). So, I want users to be able to select the status column's data and change it to any value listed in the drop down list. After the selection, they need to click a button that will update the selected row to the mySQL database.
How can I achieve this with PHP scripting and HTML?
Here is my code for displaying the data in a table on the website: (Pay no attention to phpReportGenerator.php- its only drawing the columns as per sql table)
<?php
include_once('includes/phpReportGenerator.php');
$prg = new phpReportGenerator();
$prg->width = "100%";
$prg->cellpad = "10";
$prg->cellspace = "0.5";
$prg->border = "1";
$prg->header_color = "#307D7E";
$prg->header_textcolor="#FFFFFF";
$prg->body_alignment = "left";
$prg->body_color = "#C6DEFF";
$prg->body_textcolor = "#000000";
$prg->surrounded = '1';
//$prg->font_name = "Boishakhi";
mysql_connect("localhost","username","password");
mysql_select_db("my_database");
$res = mysql_query("select * from table");
$prg->mysql_resource = $res;
//$prg->title = "Test Table";
$prg->generateReport();
?>
OR
Can somebody show me a easier/more effective way to do this?
Here is the sample code that you can use to update your mysql database by sending request to the server to access process_mysql.php :
<select onchange="update_mysql();">
<option value="1">option 1 </option>
<option value="2">option 2 </option>
</select>
Jquery function with ajax post request:
<script>
update_mysql(){
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"process_mysql.php",
data:"id="+id,
success:function(data){
alert('Successfully updated mysql database');
}
});
}
</script>

Dropdown menu not displaying change when I change product

I want to access the value selected by user for further processing.
Hence I am using post method to pass the values of whole form.
But GET to access cust_id so that I can reflect change in
further parts of my form. Hence I had to post the following line:
<select id='fullname' onChange="window.location='sp_menu.php?product='+this.value" name='fullname'>
outside php code. But now, once I select some option from dropdown menu, URL changes accordingly, but dropdown menu does not reflects the change
<?php
$query = "SELECT Cust_id, Cust_Name, Cust_City FROM Customers";
$result = mysql_query($query);
?>
<select id='fullname' onChange="window.location='sp_menu.php?product='+this.value" name='fullname'>
<?php
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['Cust_id'].'">'.$row['Cust_Name'].','.$row['Cust_City'].'</option>';
}
echo '</select>';
?>
How can I, in the same form, access the address of the particular customer id from database when user selects customer name from this dropdown menu?
I think you mean when you change dropdown, the value is not retained, it obviously won't be because your page is being refresh, you need to GET the value from url and put a selected attribute to have that value selected.
Do it this way:
<?php
$query = "SELECT Cust_id,Cust_Name,Cust_City FROM Customers" ;
$result = mysql_query($query);
//checking if GET variable is set, if yes, get the value
$selected_option = (isset($_GET['product'])) ? $_GET['product'] : '';
//we will store all the dropdown html code in a variable and display it later
$select = "<select id='fullname' onChange=\"window.location='sp_menu.php?product='+this.value\" name='fullname'>";
while($row = mysql_fetch_assoc( $result )) {
//checking if the cust_id matches the GET value,
//if yes, add a selected attribute
$selected = ($selected_option==$row['Cust_id'])?'selected':'';
echo '<option value="'.$row['Cust_id'].'"'. $selected. '>' . $row['Cust_Name'] .' , '.$row['Cust_City']. '</option>';
}
$select .= '</select>';
//display the dropdown
echo $select;
?>

select id from the select gender dropdown list

I have a dropdown list of gender. I am getting the values from my table 'candidate' and in this table i have a field which is actually a foreign key to another table.
The field is gender_code_cde, and the table name is gender_code. Now gender_code contains 2 rows. and id and a description. Its structure is like:
1->Male
2->Female
Its being displayed in dropdown list. but I want to get the id 1 if male is selected and id 2 if female is selected. My code is below:
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
I am working in codeIgniter.
// this will alert value of dropdown whenever it will change
<script>
function getvalue(val)
{
alert(val);
}
</script>
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER" id="Gender" onchange="getvalue(this.value)">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
In Javascript, you can get the value with native JS.
var e = document.getElementById("give-the-select-element-an-id");
var gender_cde = e.options[e.selectedIndex].value;
If, you want it back at the server, it will come in to PHP as $_GET['GENDER'] or $_POST['GENDER'] depending on if the form does a POST or a GET request.
If you are submitting a (POST) form and this is inside that form you can access the the value (id) from CodeIgniter's $_POST wrapper: $this->input->post('GENDER');. I don't use CodeIgniter so I could be wrong, but it will be located in your $_POST array from PHP.
If you just want to replicate the variable somewhere on the page you can just echo it. Or set via js/jQuery with document.getElementById('#something').value = value; or jQuery('#something').html(value);.
You should also change the following:
use a foreach in place of your while:
foreach ($query as $row) {
echo $row['gender_x'] . $row['gender_y'];
}
use the CodeIgniter SQL wrapper instead of depreciated PHP functions. The query part is $this->db->query('SELECT statement goes here');. You should look at your CodeIgniters' version documentation for a more in depth explanation.
EDIT: To make it a bit more clear, an example:
$query = $this->db->query('SELECT * FROM gender_code');
foreach ($query->result() as $row) {
echo '<option value="' . $row->gender_cde . '">' . $row->geneder_dsc . '</option>';
}
This is assuming you have setup the previous calls in CodeIgniter. Please see http://ellislab.com/codeigniter/user-guide/database/examples.html and you may wish to read http://ellislab.com/codeigniter/user-guide/

update database with checkbox

My database table has 2 fields: id (int) and state (enum -> 0,1).
What I need to do is to update my database (my state field) with the state of a checkbox (0 for empty, 1 for checked).
To show each of the fields in my database, I use a loop:
Loop:
<?php
foreach ( $posts_array as $module )
{
?>
<h2><?php echo $module->titre; ?></h2>
<input type="checkbox" name="chkbx_<?php echo $module->id; ?>"> id="chkbx_<?php echo $module->id; ?>" class="onoffswitch-checkbox"> On/Off <br />
<?php
}
?>
My update file:
foreach ($_GET['onoffswitch-checkbox'] as $id => $state)
{
// $_GET['onoffswitch-checkbox'] = class for all my checkboxed
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;
}
Where I need help is the AJAX part of the code. I'm guessing it looks something like this, but it doesn't seem to work:
AJAX
$(document).ready(function() {
$("onoffswitch-checkbox").click(function() {
var id = $(this).attr('id');
$("#state_span").load("module_update.php?"+id);
}
}
I've been looking around, seen a few examples where the we could do so with a submit button, but none where the information is automatically recorded when clicking the checkbox.
Try this:
AJAX
$(document).ready(function() {
$(".onoffswitch-checkbox").click(function() {
var id = this.id; //changed here also, just because jQuery is not needed here
var state = this.checked ? 1 : 0;
$("#state_span").load("module_update.php?id="+id+"&state="+state);
}
}
Changed 3 things:
added a dot in $("onoffswitch-checkbox") so its now $(".onoffswitch-checkbox")
added id= after module_update.php? and before id value.
since you need state also I added that also with a & to separate the values for $_GET in php to separate them
PHP
I don't know what you mean with $_GET['onoffswitch-checkbox'] in the php, maybe a mistake? My suggestion does not need it anyway, neither does your mysql query.
Since you will be only clicking one at a time I see no need for the foreach loop in php, so you could do this:
$id = $_GET['id'];
$state= $_GET['state'];
// $_GET['onoffswitch-checkbox'] ?? I don't think you need this...
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;

how Start PHP Session when click with jquery

i have problim in jquery
i working in interactive map, in click form href for city i wnat insert the city name or number in sql query .
this link
link citys :
<a href='#' class='city_pr' id=aden> </a>
mysql query:
$sql="select * from project where city='$_SESSION[CITY]' AND active =1 ";
How to make a change when the session to mysql query on click the link below Download Page Navigation with jquery
It is not possible to use PHP session directly with jQuery, you need to do an ajax call.
Try this.
Explanation:
This will capture the value inside the link, do a post to a PHP file and print the data in "result" div without refreshing the page.
(Don't forget to read my observation at the end of the post)
HTML:
<a href='#' id='country'>USA</a>
<br/>
<div id="result"></div>
JS:
​$('#country').click(function(){
// get the value inside the <a> tag
var country = $(this).html();
$.post('process.php', { country:country }, function(data){
// Everything is Ok, so data won't be 0
if(data != 0){
// Print country information
$('#result').html(data);
}
});
});
process.php
<?php
if($_POST() && isset($_POST['country'])){
/* Connect to DB */
$link = mysql_connect('server', 'user', 'pwd');
if (!$link) {
// No connection
print(0);
exit();
}
$db = mysql_select_db('db', $link);
if (!$db) {
// DB selection error
print(0);
exit();
}
/* sanitize the value */
$country = mysql_real_escape_string($_POST['country']);
/* do your query */
$sql = "SELECT * FROM country WHERE country_name = '$country'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
// At this point I am supposing that you stored in your table
// latitudes and longitudes of countries.
echo "Latitude is: ".$row['latitude']." Longitude is: ".$row['longitude'];
}
} else {
// No results found
print(0);
}
}
?>​
Observation:
Try using other way to send the country value to the server.
For example:
if I have:
<a href='#' id='country'>United States of America</a>
In SQL query I will have:
SELECT * FROM country WHERE country_name = 'United States of America';
A better way could be:
<a href='#' id='us'>United States of America</a>
So in my JS I will have to replace var country = $(this).html(); for this:
//outputs 'us'
var country = $(this).attr('id');
Then in your SQL query you will get this:
SELECT * FROM country WHERE country_name = 'us';
It is more reasonable to use codes and no names (names are just to show the user, for better understanding because then you will have more problems to sanitize the value for using it with your query and also use functions like trim(); to remove spaces and others). If you do that you will have to change your query to find the country by code:
SELECT * FROM country WHERE country_code = 'us';
Hope this helps :-)

Categories