I have a table with this structure and trying to use a dropdown to select a language from the list and then display the contents of respective language_id .. I am using mysql and php 5.4
My code is as follows, got stuck with looping and not sure how to get it
$sql=mysql_query("SELECT lang_id, lang_desc FROM languages ");
if(mysql_num_rows($sql))
{
$select= '<select lang_desc="select">';
while($rows=mysql_fetch_array($sql))
{
$select.='<option value="'.$rows['lang_id'].'">'.$rows['lang_desc'].'</option>';
}
}
$select.='</select>';
echo $select ;
$result = mysql_query("SELECT * FROM contents LEFT JOIN languages ON contents.lang_id = languages.lang_id WHERE contents.page_name = 'index' AND contents.lang_id = '$select'");
while ($row = mysql_fetch_array($result))
{
}
Please help
I think this want minimum 2 PHP pages 1st for show data and 2nd for creat data in hear I didn't create DB connection please add it
in 1st I use jquery for getting data from 2nd PHP
show.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<select id="lang" onchange="setlang(this.value)">
<?PHP
$sql=mysql_query("SELECT lang_id, lang_desc FROM languages");
while($rows=mysql_fetch_array($sqL,MYSQL_ASSOC)){
echo '<option value="'.$rows['lang_id'].'">'.$rows['lang_desc'].'</option>'
}
?>
</select>
<div id='dis'></div>
<script type="text/javascript">
$( document ).ready(function() {
setlang($('#lang').val());
});
function setlang(val) {
$.ajax({
url: "data.php",
type: "POST",
data:{val:val},
success: function(result){
$("#dis").html(result);
}
});
}
</script>
data.php
<?php
$result = mysql_query("SELECT * FROM contents LEFT JOIN languages ON contents.lang_id = languages.lang_id WHERE contents.page_name = 'index' AND contents.lang_id = '".$_POST['val']."'");
$data="";
while ($row = mysql_fetch_array($result))
$data.="your row data for dis";
//
}
echo $data;
?>
I currently have this code that populates one dropdown using the value from previous dropdown, my problem now is how will I populate the 3rd dropdown using the result from the 2nd dropdown that was provided by the first dropdown?
This the current code.
accounttype will be the first dropdown.
accountcode will be the second dropdown based on the result of accounttype.
accounttitle should be the third dropdown based on the result of accountcode .
<div class="">
<label>accounttype :</label>
<select name="accounttype" id="accounttype">
<option value=''>------- Select --------</option>
<?php
$sql = "SELECT DISTINCT accounttype from earningsamendmentaccount";
include 'query/sqlsrv_query-global.php';
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
echo "<option value='".$row['accounttype']."'>".$row['accounttype']."</option>";
}
}
?>
</select>
<label>accountcode :</label>
<select name="accountcode" id="accountcode"><option>------- Select --------</option></select>
<label>accounttitle :</label>
<select name="accounttitle" id="accounttitle"><option>------- Select --------</option></select>
</div>
This is currently my ajax. This is within the same pag as my <div>
<script>
$(document).ready(function() {
$("#accounttype").change(function() {
var accounttype = $(this).val();
if(accounttype != "") {
$.ajax({
url:"earnings_amendment-employee_select.php",
data:{accountcode:accounttype},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#accountcode").html(resp);
}
});
} else {
$("#accountcode").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
This is my earnings_amendment-employee_select.php .
<?php
include 'includes/session.php';
if(isset($_POST['accountcode'])) {
$accountcode=$_POST['accountcode'];
$sql = "select accountcode, accounttitle from earningsamendmentaccount where accounttype='$accountcode'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
if(sqlsrv_num_rows($query) > 0) {
echo "<option value=''>------- Select --------</option>";
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
echo "<option value='".$row['accountcode']."'>".$row['accountcode']."</option>";
}
}
} else {
header('location: ./');
}
?>
What would be the best approach to do this to populate my third dropdown column? I tried creating a separate ajax for accounttitle but it didn't work.
have you tried
$('#your_second_dropdown').on('change', ()=> {
// your code here...
})
I have 4 dynamic dependent select boxes, now I want to combine the result of the 4 selects into a query. I have all the relative code below.
font-end part of the select boxes
<form class="select-boxes" action="<?php echo site_url("/part-search-result/"); ?>" method="POST" target="_blank">
<?php include(__DIR__.'/inc/part-search.php'); ?>
</form>
part-search.php
<?php
include( __DIR__.'/db-config.php' );
$query = $db->query("SELECT * FROM ps_manufact WHERE status = 1 ORDER BY manufact_name ASC");
$rowCount = $query->num_rows;
?>
<select name="manufacturer" id="manufact" onchange="manufactText(this)">
<option value="">Select Manufacturer</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['manufact_id'].'">'.$row['manufact_name'].'</option>';
}
}else{
echo '<option value="">Manufacturer Not Available</option>';
}
?>
</select>
<input id="manufacturer_text" type="hidden" name="manufacturer_text" value=""/>
<script type="text/javascript">
function manufactText(ddl) {
document.getElementById('manufacturer_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="type" id="type" onchange="typeText(this)">
<option value="">Select Manufacturer First</option>
</select>
<input id="type_text" type="hidden" name="type_text" value=""/>
<script type="text/javascript">
function typeText(ddl) {
document.getElementById('type_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="year" id="year" onchange="yearText(this)">
<option value="">Select Type First</option>
</select>
<input id="year_text" type="hidden" name="year_text" value=""/>
<script type="text/javascript">
function yearText(ddl) {
document.getElementById('year_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="model" id="model" onchange="modelText(this)">
<option value="">Select Year First</option>
</select>
<input id="model_text" type="hidden" name="model_text" value=""/>
<script type="text/javascript">
function modelText(ddl) {
document.getElementById('model_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<input type="submit" name="search" id="search" value="Search">
<script type="text/javascript">
jQuery(function($) {
$('#manufact').on('change',function(){
var manufactID = $(this).val();
if(manufactID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'manufact_id='+manufactID,
success:function(html){
$('#type').html(html);
$('#year').html('<option value="">Select Type First</option>');
}
});
}else{
$('#type').html('<option value="">Select Manufact First</option>');
$('#year').html('<option value="">Select Type First</option>');
}
});
$('#type').on('change',function(){
var typeID = $(this).val();
if(typeID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'type_id='+typeID,
success:function(html){
$('#year').html(html);
$('#model').html('<option value="">Select Year First</option>');
}
});
}else{
$('#year').html('<option value="">Select Type First</option>');
$('#model').html('<option value="">Select Year First</option>');
}
});
$('#year').on('change',function(){
var yearID = $(this).val();
if(yearID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'year_id='+yearID,
success:function(html){
$('#model').html(html);
}
});
}else{
$('#model').html('<option value="">Select Year First</option>');
}
});
});
</script>
ajax-data.php
<?php
include( __DIR__.'/db-config.php' );
if(isset($_POST["manufact_id"]) && !empty($_POST["manufact_id"])){
$query = $db->query("SELECT * FROM ps_type WHERE manufact_id = ".$_POST['manufact_id']." AND status = 1 ORDER BY type_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Type</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['type_id'].'">'.$row['type_name'].'</option>';
}
}else{
echo '<option value="">Type Not Available</option>';
}
}
if(isset($_POST["type_id"]) && !empty($_POST["type_id"])){
$query = $db->query("SELECT * FROM ps_year WHERE type_id = ".$_POST['type_id']." AND status = 1 ORDER BY year_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Year</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['year_id'].'">'.$row['year_name'].'</option>';
}
}else{
echo '<option value="">Year Not Available</option>';
}
}
if(isset($_POST["year_id"]) && !empty($_POST["year_id"])){
$query = $db->query("SELECT * FROM ps_model WHERE year_id = ".$_POST['year_id']." AND status = 1 ORDER BY model_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Model</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['model_id'].'">'.$row['model_name'].'</option>';
}
}else{
echo '<option value="">Model Not Available</option>';
}
}
?>
part-search-result.php
<?php
if (isset($_POST['search'])) {
$clauses = array();
if (isset($_POST['manufacturer_text']) && !empty($_POST['manufacturer_text'])) {
$clauses[] = "`manufacturer` = '{$_POST['manufacturer_text']}'";
}
if (isset($_POST['type_text']) && !empty($_POST['type_text'])) {
$clauses[] = "`type` = '{$_POST['type_text']}'";
}
if (isset($_POST['year_text']) && !empty($_POST['year_text'])) {
$clauses[] = "`year` = '{$_POST['year_text']}'";
}
if (isset($_POST['model_text']) && !empty($_POST['model_text'])) {
$clauses[] = "`model` = '{$_POST['model_text']}'";
}
$where = !empty( $clauses ) ? ' where '.implode(' and ',$clauses ) : '';
$sql = "SELECT * FROM `wp_products` ". $where;
$result = filterTable($sql);
} else {
$sql = "SELECT * FROM `wp_products` WHERE `manufacturer`=''";
$result = filterTable($sql);
}
function filterTable($sql) {
$con = mysqli_connect("localhost", "root", "root", "i2235990_wp2");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$filter_Result = mysqli_query($con, $sql);
return $filter_Result;
}
?>
<?php get_header(); ?>
<div class="container">
<div id="products" class="row list-group">
<?php while ( $rows = mysqli_fetch_array($result) ): ?>
<div class="item col-xs-12 col-sm-4 col-md-4 col-lg-4">
<div class="thumbnail">
<?php
echo '<img name="product-image" class="group list-group-image hvr-bob" src=' . $rows['image_url'] . ' width="400px" height="250px" alt="" />';
?>
<div class="caption">
<h4 class="group inner list-group-item-heading">
<?php
echo "Manufacturer:\t".$rows['manufacturer'].'<br>';
echo "Type:\t".$rows['type'].'<br>';
echo "Year:\t".$rows['year'].'<br>';
echo "Model:\t".$rows['model'].'<br>';
echo '<br>';
echo "Description:\t".$rows['description'].'<br>';
?>
</h4>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
<?php get_footer(); ?>
Now my problem is:
If only select the first one box, or select the first two boxes, and click the Search button, it successfully jumps to the result page. However, if continuously select the third box, the result page is gone and Chrome Console returns the error:
Failed to load resource: the server responded with a status of 404 (Not Found)
Let me ask you a question. You've tagged this as a WordPress website. Correct? Then why aren't you using the built-in database handler, $wpdb to both prepare and communicate with the database? It's the safest and fastest way for you to work with the database.
Revised Code
Here I've revised your code to do the following:
Use $wpdb->prepare to sanitize the $_POST values to protect the database from nefarious folks
Remove redundancies by looping through a list of column names and using the field naming pattern you specified by suffixing _text to the column name
Using $wpdb->get_results() to go fetch the results.
Here is the revised code:
/**
* Build the search's WHERE SQL from the form's $_POST fields.
*
* #since 1.0.0
*
* #return string
*/
function build_search_where_sql() {
global $wpdb;
$column_names = array(
'manufacturer',
'type',
'year',
'model',
);
$where_clauses = [];
foreach( $column_names as $column_name ) {
$post_key = $column_name . '_text';
if ( isset( $_POST[ $post_key ] ) && $_POST[ $post_key ] ) {
$where_clauses[] = $wpdb->prepare( "{$column_name} = %s", $_POST[ $post_key ] );
}
}
if ( empty( $where_clauses ) ) {
return '';
}
$where_sql = " WHERE " . join( ' AND ', $where_clauses );
return $where_sql;
}
/**
* Get the search results from the database. If the records
* do not exist or an error occurs, false is returned. Else,
* an array with stdClass objects for each record is returned.
*
* #since 1.0.0
*
* #return bool|array
*/
function get_search_database_results() {
$where_sql = isset( $_POST['search'] )
? build_search_where_sql()
: "WHERE manufacturer = ''";
if ( ! $where_sql ) {
return false;
}
global $wpdb;
$sql_query = "SELECT * FROM wp_products {$where_sql};";
$records = $wpdb->get_results( $sql_query );
if ( ! $records ) {
return false;
}
return $records;
}
UPDATE: Strategy for You
Now that I've seen the HTML code you are proposing as well as knowing you are learning about building websites, let's talk about a different architectural strategy for your project.
Don't use a custom database table.
Use a custom post type called products instead.
Use post metadata to set the attributes for each product, i.e. the manufacturer, model, year, type, etc.
Use a form plugin, such as Ninja Forms.
You can build the meta boxes yourself for the metadata, if you have the technical chops to do it. Else, you can use a third-party plugin such as CMB2 or ACF.
Custom Post Type
WordPress provides you the ability to add custom content. They provide built-in post types. We developers can add custom ones that are specific content context. Products is a good candidate for a custom post type.
You can generate the code on GenerateWP. It's literally a few lines of code to create it.
Where can you learn about Custom Post Types?
Well, there are plenty of tutorials. Codex gives you the documentation and examples. I teach it at Know the Code. Tuts+ has lots of tutorials. And many others....
Why Custom Post Type Instead of Custom Db Table?
Yes, you can build a custom database table. But it requires you to add the schema, seed the table, write the interface for admins to interact with the content, and then write and secure the interaction. To populate the options in the select, you'd have to query the database using $wpdb and then write a model to translate it into a view. Then you'd have to write the form processing to interact and save.
In other words, it's going to cost you time and money. Why? Because it's more code and not native to WordPress. You have to write, secure, test, and maintain it yourself.
If You Want to Stick With Your Current Strategy
If you prefer to stick with the custom database table strategy, then here are some suggestions to help you out:
You don't need the hidden input for each of the select elements. Why? When the form is posted, the option set for each select will post back to the server.
I'd change the select names to be an array, like this: name="part-select[manufacturer]" and then repeat for type, model, year, etc. Then you can grab the $_POST['part-select'] to get all of the values.
You are going to want to add nonce to protect the content. Make sure to pass it with the data packet when doing AJAX too.
Using AJAX, you can request the records from the database. You'll need to modify the code I gave to you in order to build the SQL query. Then loop through the results to build the HTML you want to send back to the front-end.
I like building the HTML markup on the server side and then sending that back to the front-end when doing AJAX.
Cheers.
i am working with interlinked dropdown list i.e on selection of one dropdown list ajax call generated and populated another dropdown list and so on.
So my problem is with data coming from server side,on selection of each dropdown list i want to filter the available-results also,but the data that coming from server side get appended to show div i.e dropdown-list items and results-items.i only want to append results-items to show div.
client side code
var country_code = $(this).val();
console.log(country_code);
if(country_code){
$('#loadingmessage').show();
$.ajax({
type:'POST',
url:'dependent.php',
data:'country_code='+country_code,
success:function(html){
console.log(html);
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
$('#results').html(html);
$('#loadingmessage').hide();
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
server side code
if(isset($_POST["country_code"]) && !empty($_POST["country_code"])){
$id = 1;
$code = $_POST['country_code'];
$code = mysqli_real_escape_string($conn,$code);
$query = "SELECT * FROM plus2_state WHERE country_code = '$code' ORDER BY state ASC";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$rowCount = mysqli_num_rows($result);
if($rowCount > 0){
while($row = mysqli_fetch_array($result)){
echo '<option class="state_option" value="'.$row['state_id'].'">'.$row['state'].'</option>';
}
}else{
echo '<option class="state_option" value="">State not available</option>';
}
$query_1 = "SELECT * from content where country_code = '$code' ORDER BY emp_name ASC";
$result_1 = mysqli_query($conn,$query_1) or die(mysqli_error($conn));
$row_count = mysqli_num_rows($result_1);
$_SESSION['result'] = array();
if($row_count > 0 )
{
while($content_rows = mysqli_fetch_array($result_1))
{
unset($_SESSION['result']);
echo "<div class='result'><div class='col-md-3 photo-grid' style = 'float:left'>
<div class = 'well well-sm'><h4><small>".$content_rows['emp_name']."</small></h4></div></div></div>";
$_SESSION['result'][$id] = array('name' => $content_rows['emp_name']);
}
}
else
{
echo "<div class = 'result'>no results found</div>";
}
$_SESSION['country_code'] = $code ;
//print_r($_SESSION['result']);
}
I am not posting here complete code yet I want an idea how to retrieve data in checboxes based on a dropdown list. I have a dropdownlist of users, and pages data in checkboxes.
Suppose table user have two columns (user_id, user) and pages have three columns (page_id, user_id, title).
I wish these cheboxes automatic check/uncheck acording to selected user without refreshing page. Suppose I am fetching users as
echo '<select name="user_id">';
echo '<option value="">Select User</option>';
$sql = "SELECT * from users";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
$uid = $row['user_id'];
$user = $row['user'];
echo '<option value="'.$uid.'">'.$user.'</option>';
}
echo '</select>';
And data in checkboxes on the basis of selected user (make sure user_id is compared in IF condition but not in query)
$user_id = $_POST['user_id']; //selected user from list
$query = "SELECT * from pages";
$result = mysql_query($query);
while($rowPage = mysql_fetch_assoc($result)) {
$upid = $rowPage['user_id'];
$pid = $rowPage['page_id'];
$title = $rowPage['title'];
if($upid == $user_id) {
echo '<input type="checkbox" name="userPages[]" value="'.$pid.'" checked="checked"> '.$title;
} else {
echo '<input type="checkbox" name="userPages[]" value="'.$pid.'"> '.$title;
}
}
How is it possible in Ajax/Jquery I mean without refreshing page.
Hope you understand what I mean.
Thanks
here is the asnwer what you can do is like this
echo '<select name="user_id" id="userCombo">';
echo '<option value="">Select User</option>';
$sql = "SELECT * from users";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
$uid = $row['user_id'];
$user = $row['user'];
echo '<option value="'.$uid.'">'.$user.'</option>';
}
echo '</select>';
echo '<div id="userCheckBoxes"></div>'
Now put the ajax call on the change event of the select box.
I am here going to use jquery ajax.
<script type="text/javascript">
$(document).ready(function()
{
$("#userCombo").change(function()
{
var id=$(this).val();
var dataString = 'user_id='+ id;
$.ajax
({
type: "POST",
url: "ajax_checkboxes.php",
data: dataString,
cache: false,
success: function(html)
{
$("#userCheckBoxes").html(html);
}
});
});
});
</script>
Now make ajax_checkboxes.php into same directory.
then put your below code into the ajax_checkboxes.php. I assume you can make database connectivity and all by your self.
$user_id = $_POST['user_id']; //selected user from list
$query = "SELECT * from pages";
$result = mysql_query($query);
while($rowPage = mysql_fetch_assoc($result)) {
$upid = $rowPage['user_id'];
$pid = $rowPage['page_id'];
$title = $rowPage['title'];
if($upid == $user_id) {
echo '<input type="checkbox" name="userPages[]" value="'.$pid.'" checked="checked"> '.$title;
} else {
echo '<input type="checkbox" name="userPages[]" value="'.$pid.'"> '.$title;
}
}
I did not taste it on my local server but I am sure It will work.
PS dont for get to include jQuery on the head section of your site.