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;
?>
Related
This is my html data:
<select class='ssc' id="selectCity" name='bachelorInstituteType' style='width: 200px;'>
<option value=""></option>
</select>
Chosen js and ajax to load data from database ---
$(document).ready(function() {
$(".ssc").chosen();
function loadlocation() {
$.ajax({
url: "loadlocation.php",
type: "POST",
success: function(data) {
$("#selectCity").append(data);
}
});
};
loadlocation();
});
loadlocation.php page data :
<?php
include "./includes/connection.php";
$sql = "SELECT * FROM city";
$result = mysqli_query($conn, $sql);
$data= "";
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data.= "<option value='{$row['cityName']}'> {$row['cityName']} </option>";
}
}
echo $data;
?>
here (cityName) data is coming form database. The problem is chosen select box is not showing the data but if I make a simple dropdown then it works. Please give me a solution.
I have been searching everywhere on this website and tried many solutions but none worked for me ! My problem is the following :
I have 2 tables :
TABLE INFO_STATUS (status_id, status_desc)
and
TABLE INFO_MARQUES (comp_id, comp_desc, comp_status(INT))
I am linking comp_status and status_id so that the row in INFO_MARQUES will get the current status.
What I would like to do? (EDITED FROM HERE)
2. get the current status value of info_marques located in comp_status automatically selected in the dropdown list when I open the update form
Example I want to update this company :
comp_id : 15
comp_desc : WEISS
comp_status : 1
Assuming that in table info_status :
status_id = 1
status_desc = FOLLOW-UP
When I open the update form I want to see this :
Check this
My Modal : (WORKING)
<select class="form-control" name="select_status">
<option value=''>Selectionner</option>
<?php
try {
$user = new USER();
$output = array();
$stmt = $user->runQuery("SELECT * FROM info_status");
$stmt->execute();
$result=$stmt->fetchAll();
foreach($result as $row) {
echo '<option value='.$row["status_id"].'>'.$row["status_desc"].'</option>';
}
}
catch(PDOException $e) {
printf('Erreur MySQL %d : %s', $e->getCode(), $e->errorInfo[2]);
exit;
}
?>
</select>
My Ajax
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
$.ajax({
url:"partials/test/fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#comp_name').val(data.comp_name);
$('#comp_parent').val(data.comp_parent);
$.each($('.select_status option'),function(a,b){
if($(this).val()== data.comp_status){
$(this).attr('selected',true)
}
});
$('.modal-title').text("Modifier un fichier client");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.user_image);
$('#action').val("Edit");
$('#operation').val("Edit");
}
})
});
then my PHP page : (WORKING)
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connection->prepare(
"SELECT *
FROM info_marques AS m
LEFT JOIN info_status AS s
ON s.status_id = m.comp_status
WHERE m.id = '".$_POST["user_id"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["comp_name"] = $row["comp_name"];
$output["comp_parent"] = $row["comp_parent"];
$output["comp_status"] = $row["status_desc"];
}
echo json_encode($output);
}
What am I missing here?
Cheers
I am not sure that if you want to populate drop down or else select data based on your response, But if you want to select the data and you have options already in drop down, you can do this:
$.each($('#select_status option'),function(a,b){
if($(this).val() == data.comp_status){
$(this).attr('selected',true)
}
});
But if you want to populate, you will have to append it using .append(). Do let me know if issue is something different and I may give you a solution.
As you are saying you need all the status and then show the current status. what i would suggest is use .done() method of ajax. It will come handy, like:
$("#select_status").prop('disabled',true)
$('#select_id').append('<option>Please wait... Fetching status</option>');
var status_options;
$.ajax({
url:"your_page_for_all_status.php",
success: function(e){
//add <option> tags to a variable using loop
}
}).done(function(){
$.ajax({
//ajax call to get current data. Compare and select data here. write your $.each here
}).done(function(){
$("#select_status").prop('disabled',false);
});
});
You should be good to go now!!! I am sorry if I made it complex.
I have found a solution that worked but not sure it is very clean though.
For those interested to know:
HTML
<select class="form-control" name="select_status" id="status">
<option value=''>Selectionner</option>
<?php
try {
$user = new USER();
$output = array();
$stmt = $user->runQuery("SELECT * FROM info_status");
$stmt->execute();
$result=$stmt->fetchAll();
foreach($result as $row) {
echo '<option value='.$row["status_id"].'>'.$row["status_desc"].'</option>';
}
}
catch(PDOException $e) {
printf('Erreur MySQL %d : %s', $e->getCode(), $e->errorInfo[2]);
exit;
}
?>
</select>
We list down all options in my table into the dropdown list
AJAX
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"partials/test/fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#comp_name').val(data.comp_name);
$('#comp_parent').val(data.comp_parent);
$('#status').val(data.select_status);
fetching the right value from PHP page and sending to dropdown list so that this value is selected while opening the form (THE PROBLEM WAS HERE)
$('.modal-title').text("Modifier un fichier client");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.user_image);
$('#action').val("Edit");
$('#operation').val("Edit");
}
})
});
PHP
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connection->prepare(
"SELECT *
FROM info_marques AS m
LEFT JOIN info_status AS s
ON s.status_id = m.comp_status
WHERE m.id = '".$_POST["user_id"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["comp_name"] = $row["comp_name"];
$output["comp_parent"] = $row["comp_parent"];
$output["status"] = $row["status_id"];
we return the match value
}
echo json_encode($output);
}
I have a dropdown which gets the information from a query using mysqli_query()
now, once selecting a choice from the first dropdown I want the second dropdown to be filled with data from a difference query.
This is my code
HTML:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$('.country').on('change', function() {
// Code to add country information in url
location.href = location.href.split('?')[0]
+ ['?country', $(this).val()].join('=');
});
});
</script>
PHP First dropdown:
<?php
$countries = mysqli_query($mysqli,"select source from nhws.masterkey group by source;");
echo "<select name='country' style=width:200px>";
echo "<option size =30 ></option>";
while($row = mysqli_fetch_array($countries)){
echo "<option value='".$row['source']."'>".$row['source']."</option>";
}
echo "</select>";
?>
PHP Second dropdown:
<?php
if (isset($_GET['country'])) {
$country = $_GET['country'];
echo $country;
$variables = mysqli_query($mysqli,"select variable from nhws.num_all_{$country} group by variable;");
echo "<select name='variable' style=width:200px>";
echo "<option size =30 ></option>";
while($row = mysqli_fetch_array($variables)) {
echo "<option value='".$row['variable']."'>".$row['variable']."</option>";
}
echo "</select>";
}
?>
Now, once a selection was choosen from the first dropdown nothing happens in the second dropdown.
Thanks!
I assume you can use jQuery. So add a jQuery listener like this:
<script>
$(document).ready(function() {
$('.country').on('change', function() {
// Code to add country information in url
location.href = location.href.split('?')[0]
+ ['?country', $(this).val()].join('=');
});
});
</script>
Now on php code at the top add something like this after the code you mentioned
if (isset($_GET['country']) {
$country = $_GET['country'];
// code to prevent SQL injection
// ... code to get data from DB using country name
// ... code to print a new select box based on data from DB
}
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script>
$(document).ready(function() {
var $article = null;
$('#category').change(function() {
var $categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo('.query');
}
$("#business").load("php.php");
});
});
</script>
This is what I am currently doing, I am loading the php.php script, instead I want to pass the value of $categoryName to the WHERE clause in my query so it's like this:
<?php
$con = mysqli_connect(,,,,);
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
$result = mysqli_query($con,"SELECT Bname, Category FROM Business WHERE Category='$categoryName'");
while($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['Bname']."'>".$row['Bname']."</option>";
}
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
The way this should work is, the first select box is populated by php on my server showing a list of categories. A user selects a category from that box and onchange, a second select box is created, added to the form, and will query, to populate all of the business name's listed in my database that share a category(i.e the selectedindex from the first box) Can you help me change this to work how I need it to?
UPDATE: This is the updated code, now the second select box never loads.
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script>
$(document).ready(function () {
var $article = null;
$('#category').change(function () {
var categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo ('.query');
$("#business").load( "php.php",
data:{myVar:$categoryName}
);
}
});
});
</script>
Heres the php.php
<?php
$con = mysqli_connect(,,,,);
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
$myVar = $_GET["myVar"];
$result = mysqli_query($con,"SELECT Bname, Category FROM Business WHERE Category='$myVar'");
while($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['Bname']."'>".$row['Bname']."</option>";
}
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
As seen below you can make a data object with one parameter myVar
JS:
$('#category').change(function() {
var $categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo('.query');
}
$("#business").load("php.php",
data:{myVar:$categoryName}
);
});
Then get the variable in PHP like this
PHP:
$con = mysqli_connect(,,,,);
$myVar = $_GET["myVar"];
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
Inside my page I have an input ("Model") with a datalist attribute and a select menu ("Brand"). When a user select one of the options of the datalist from the Model, it will dynamically change the options value from the Brand select menu. Both options value from Model and Brand are called from the database. This is what I code so far;
<input type="text" name="type" id="type" list="datalist1" onchange="fw();"/>
<datalist id="datalist1">
<?php
$query9 = "SELECT DISTINCT model FROM server ORDER BY model ASC";
$result9 = mysql_query($query9);
while($row9 = mysql_fetch_assoc($result9))
{
echo '<option value="'.$row9['model'].'">';
} ?>
</datalist>
<select name="brand" id="test2"><option value="">-- Select Brand--</option></select>
Script;
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function fw()
{
var selname = $("#type").val();
$.ajax({ url: "getBrand.php",
data: {"brand":brand},
type: 'post',
success: function(output) {
document.getElementById('test2').options.length = 0;
document.getElementById('test2').options[0]=new Option(output,output);
// document.getElementById('test2').options[1]=new Option(output,output);
}
});
}
</script>
getBrand.php
<?php
define('DB_HOST1', 'localhost');
define('DB_NAME1', 'standby');
define('DB_USER1', 'root');
define('DB_PASS1', '');
$link = mysql_connect(DB_HOST1, DB_USER1, DB_PASS1);
if(!$link)
{
exit('Cannot connect to server "' . DB_HOST1 . '"');
}
mysql_select_db(DB_NAME1, $link) or die('Cannot use database "' . DB_NAME1 . '"');
if (isset($_POST['brand'])) {
$selname = $_POST['brand'];
$query = "SELECT * FROM server WHERE model='$brand'";
$res = mysql_query($query);
$aBrand= array();
while($rows = mysql_fetch_assoc($res)) {
$brand= $rows['brand'];
$aBrand[] = $brand;
echo $aBrand[0];
echo $aBrand[1];
}
} ?>
From what I have coded, I have succesfully change the select menu dynamically but there is one problem. When there is more one data is called from getBrand.php, the 'output' in the select menu will combine all of the data into one line. For example, if the data is "M3000" and "M4000", it will display as "M3000M4000". Now, how do I split it and make it as a normal select options?
I'm still learning Javascript and I hope anyone here can guide me.
NOTE : The code only works in Firefox because of the datalist attribute
Send your data from getBrand.php as
echo implode(";", $aBrand);
this will generate a string like M3000;M4000;M5000;M6000
and in your java script code break the string into array using this code.
StrArr = Str.split (";");
here 'Str' is your output given by getBrand.php, and 'StrArr' is the array which contains your brands.
add a special character in the string returned form php
PHP
elementcount=0;
while($row9 = mysql_fetch_assoc($result9))
{
if(elementcount>0)
echo '$<option value="'.$row9['model'].'">';//place a $ sign in start or you can for any special character
else
echo '<option value="'.$row9['model'].'">';
}
now in javascript
success: function(output) {
output = output.split("$");
document.getElementById('test2').options.length = 0;
//here now loop through the elements and add
for(var i=0,i<output.length-1)
document.getElementById('test2').options[0]=new Option(output[i],output[i]);
// document.getElementById('test2').options[1]=new Option(output,output);
}