I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
You may try something like this:
Category
<select name="supplier" style="text-transform:uppercase;" onchange = "GetChangedValue(this);">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<script>
function GetChangedValue(e) {
var value = e.options[e.selectedIndex].text;
alert(value);
}
</script>
To get the selected text, you can use Javascript
var element = document.getElementById("mySelectTag");
var selected_text = element.options[element.selectedIndex].text;
To get a substring of a text, use Javascript, for example:
selected_text.substring(0,3)
function change(){
var selectedtext = document.getElementById("idselect").value;
document.getElementById("myTextField").value = selectedtext.substring(0,3);
}
<h1 id="title">Javascript example</h1>
<input type="text" id="myTextField"/>
<select id="idselect" onchange="change()">
<option>Choose one</option>
<option value="BLUE">Blue</option>
<option value="YELLOW">Yellow</option>
<option value="RED">Red</option>
</select>
http://jsfiddle.net/Fx5T8/
Related
I am working on a project and am still relatively new to PHP. I am attempting to run a for loop which counts the number of times each flower is selected from a select list off of an HTML page. I am continuously getting "1" for all 3 flower types after choosing different combinations from the select lists during testing. If anyone has any input as to where my mistakes are I would greatly appreciate it! Here is my HTML code:
<html>
<head>
</head>
<body>
<h1>FLOWERS</h1>
<form action = 'php 08.php' method = 'post'>
<select id = '0' name = '0'>
<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>
</select>
<br><br>
<select id = '1' name = '1'>
<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>
</select>
<br><br>
<select id = '2' name = '2'>
<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>
</select>
<br><br>
<select id = '3' name = '3'>
<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>
</select>
<br><br>
<select id = '4' name = '4'>
<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>
</select>
<br><br>
<input type = 'submit' id = 'go' value = 'COUNT'>
</form>
</body>
</html>
Here is my PHP code:
<?php
$marigold = $_POST['marigold'];
$rose = $_POST['rose'];
$tulip = $_POST['tulip'];
for ($i = 0; $i <= 4; $i++) {
if ($i == 'marigold') {
$marigold++;
};
if ($i == 'rose') {
$rose++;
};
if ($i == 'tulip') {
$tulip++;
};
};
echo "MARIGOLD <span id = 'marigold'>$marigold</span>";
echo "<br><br>";
echo "ROSE <span id = 'rose'>$rose</span>";
echo "<br><br>";
echo "TULIP <span id = 'tulip'>$tulip</span>";
?>
If you want to keep your HTML like this, your PHP code should be like that:
//Initialise your counter
$marigold=$rose=$tulip=0
for ($i = 0; $i <= 4; $i++) {
if ($_POST[$i] == 'marigold') {
$marigold++;
}
if ($_POST[$i] == 'rose') {
$rose++;
}
if ($_POST[$i] == 'tulip') {
$tulip++;
}
}
echo "MARIGOLD <span id = 'marigold'>$marigold</span>";
echo "<br><br>";
echo "ROSE <span id = 'rose'>$rose</span>";
echo "<br><br>";
echo "TULIP <span id = 'tulip'>$tulip</span>";
Ok so I have three tables which contains list World's countries their states and their cities for my registration form. The problem is that the list of the cities is too huge. It contains 48,314 entries in total. So my site is getting hanged and the browser is showing messages to stop script. I am using mozilla for browser purpose.
This is the code I am using to get the cities, states and countries:
$country = "SELECT * FROM countries";
$country = $pdo->prepare($country);
$country->execute();
$state = "SELECT * FROM states";
$state = $pdo->prepare($state);
$state->execute();
$city = "SELECT * FROM cities";
$citq = $pdo->prepare($city);
$citq->execute();
This is my jQuery code:
$(document).ready(function () {
$("#country").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#state option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#state').html('<option value="">Select State</option>').append(options);
});
$("#state").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#city option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#city').html('<option value="">Select City</option>').append(options);
});
});
This is my HTML:
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="state" id="state">
<option value="">Select State</option>
<?php while($j = $state->fetch()){ extract($j); ?>
<option value="<?php echo $country_id; ?>" data="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="city" id="city">
<option value="">Select City</option>
<?php while($k = $citq->fetch()){ extract($k); ?>
<option value="<?php echo $id ; ?>" data="<?php echo $state_id; ?>"><?php echo $name ; ?></option>
<?php } ?>
</select>
Now can anyone please help me getting a solution as to how I can load it completely smoothly without getting my site hanged whenever the page is refreshed?
You could load the states and cities dynamically once the "parent" selection is made. This would reduce the amount of data.
No clear code because I think you know what you are doing, but the idea:
-> [html] select
-> [js] onChange call php with ajax
-> [php] SQL select states where country="chosencountry"
-> [js] update form/selectbox
EDIT: (code)
JS:
<script>
function BuildSelectbox(job,parent) {
try { req = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { /* No AJAX Support */ }
req.open('get','subselects.php?job='+job+'&parent='+parent);
/* let the php echo the resultvalue */
req.onreadystatechange = function() {
handleResponse(div);
};
req.send(null);
}
function handleResponse(div) {
if ((req.readyState == 4) && (req.status == 200)) {
document.getElementById(job).value=req.responseText;
}
}
</script>
PHP part: (subselects.php)
<?
if ($_GET["job"]=="states") {
// assuming there is a key country in states
$state = "SELECT * FROM states where country=".$_GET["parent"];
$state = $pdo->prepare($state);
$state->execute();
} else {
// assuming there is a key state in cities
$city = "SELECT * FROM cities where state=".$_GET["parent"];
$citq = $pdo->prepare($city);
$citq->execute();
}
// echo the whole selectbox
echo '<select id="'.$_GET["job"].'">';
// put the option loop from your queryresult here
echo '</select>';
?>
HTML:
<div id="countries" onChange="BuildSelectbox('states',this.selectedIndex);>
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
</div>
<div id="states"></div>
<div id="cities"></div>
This dynamically generates full selectboxes and puts them into the empty divs "states and "cities". Of course you need to output the selectbox in the php code. Parent of states is country and parent of cities is states. Hope this explains it.
I have a sql table looks like this.
id name cname
1 Ash abc
2 Ash abc
3 Ashu abc
4 Ashu xyz
5 Yash xyzz
6 Ash xyyy
I want user to select a value from first select drop down list that shows DISTINCT name values and its working fine.
1st Select:
<select id="select1" required="required" class="custom-select standard">
<option value="0" selected="selected">Choose Category</option>
<?php
$resultd = mysqli_query($mysqli,"SELECT DISTINCT name FROM advertise");
if ($resultd)
{
while($tier = mysqli_fetch_array($resultd))
{
echo '<option value="' .$tier['name'] . '">' . $tier['name'] . '</option>';
}
}
?>
</select>
now i want to show values of second select drop down box based on first. Jquery i am using for this is :
<script>
$(function(){
var conditionalSelect = $("#select2"),
// Save possible options
options = conditionalSelect.children(".conditional").clone();
$("#select1").change(function(){
var value = $(this).val();
conditionalSelect.children(".conditional").remove();
options.clone().filter("."+value).appendTo(conditionalSelect);
}).trigger("change");
});
</script>
2nd Select Box
<select id="select2" required="required" class="custom-select standard">
<option value="0" selected="selected">Choose Location</option>
<option class="conditional name" value="">cname</option>
</select>
All i want to know is what php query should i need to use to get values in 2nd select box based on first. I tried a lot to find solutions but i didn't find any solution that gets its values from database...Thanks in advance...
You may not need a 2nd Query and all those complexities if you do things a little differently. This means, you could achieve your goal using one single Query. The Code below demonstrates how. Note: This Solution uses JQuery to make things simpler.
To test this; just copy and paste the Code AS IS into a new File and see if it works as you had expected.
CHEERS & GOOD-LUCK!!!
<?php
// USE YOUR CONNECTION DATA... PDO WOULD BE HIGHLY RECOMMENDED.
// INTENTIONALLY USING mysqli (NOT RECOMMENDED) TO MATCH YOUR ORIGINAL POST.
$conn = mysqli_connect("localhost", "root", 'root', "test");
if (mysqli_connect_errno()){
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$resourceID = mysqli_query($conn, "SELECT * FROM advertise");
$all = mysqli_fetch_all($resourceID, MYSQLI_ASSOC);
$uniques = [];
$options1 = "";
if( !empty($all) ){
foreach($all as $intKey=>$advertiseData) {
$key = $advertiseData['name'];
$cName = getCNameForName($all, $key);
if (!array_key_exists($key, $uniques)) {
$uniques[$key] = $advertiseData;
$options1 .= "<option value='{$key}' data-cname='{$cName}'>";
$options1 .= $key . "</option>";
}
}
}
function getCNameForName($all, $name){
$result = [];
foreach($all as $iKey=>$data){
if($data["name"] == $name){
$result[] = $data['cname'];
}
}
return $result ? implode(", ", array_unique($result)) : "";
}
?>
<html>
<body>
<div>
<select id="select1" required="required" class="custom-select standard">
<option value="0" selected="selected">Choose Category</option>
<?php echo $options1; ?>
</select>
<select id="select2" required="required" class="custom-select standard">
<option value="0" selected="selected">Choose Location</option>
</select>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
var firstSelect = $("#select1");
var secondSelect = $("#select2");
firstSelect.on("change", function(){
var main = $(this);
var mainName = main.val();
var mainCName = main.children('option:selected').attr("data-cname");
var arrCName = mainCName.split(", ");
var options2 = "<option value='0' selected >Choose Location</option>";
for(var i in arrCName){
options2 += "<option value='" + arrCName[i] + "' ";
options2 += "data-name='" + mainName + "'>" + arrCName[i] + "</option>\n";
}
secondSelect.html(options2);
});
});
})(jQuery);
</script>
</body>
</html>
I am looking for a way to search for data from the database using input type box list, I tried make the code but it doesn't display anything:
html code:
<form action="users.php" method="post" name="searching">
<select name="users">
<option selected="selected" value="">-- select --</option>
<option value="1">user1</option>
<option value="2">user2</option>
<option value="3">user3</option>
</select>
<input type="submit" name="search" value="find">
</form>
php code:
if (isset($_POST['users'])) {
$key = trim ($_POST['users']);
$s = "SELECT * FROM users where user_name LIKE '%$key %'";
$res = mysql_query($s) or die('query did not work');
while($row = mysql_fetch_array( $res ))
{
?>
User ID: <?php echo $row['user_id'] ?>
User Name: <?php echo $row['user_name'] ?>
<?php
}
?>
when I try the code I didn't get any result and when I remove the while loop and put this instead of it :
<?php echo $key; ?>
it gives me the numbers of the selected value, for example if I select user2 the result will be 2. and I want the result to be user id and user name.
you need to fetch all the user name in your drop down select box
<select name="users">
<option selected="selected" value="">-- select --</option>
<?php $s2 = "SELECT * FROM users";
$q2=mysql_query($s2) or die($s2);
while($rw=mysql_fetch_array($q2))
{
echo '<option value="'.$rw['userid'].'">'.$rw['username'].'</option>';
}</select>
?>
<?php if (isset($_POST['search'])) { // submit button name here
$key = $_POST['users'];
$s = "SELECT * FROM users where user_id='".$key."'";
$res = mysql_query($s) or die($s);
while($row = mysql_fetch_array( $res ))
{
?>
User ID: <?php echo $row['user_id'] ?>
User Name: <?php echo $row['user_name'] ?>
<?php
}
?>
edit your html to this,you will get the in $_POST which will be in value='something'
<form action="users.php" method="post" name="searching">
<select name="users">
<option selected="selected" value="">-- select --</option>
<option value="user1">user1</option>
<option value="user2">user2</option>
<option value="user3">user3</option>
</select>
<input type="submit" name="search" value="find">
</form>
Or if value is the id of user then change query to this
$s = "SELECT * FROM users where user_id='".$key."'";
I am using the given code below to populate some values from a column of a table. It's just getting filled blank..
Can you please find the problem with it ?
<select name="category">
<option value="" selected>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("muskilaasaan");
$category = "SELECT cat FROM category";
$query_result = mysql_query($category);
while($result = mysql_fetch_array($query_result))
{
?>
<option value = "<?php echo $result['cat']?>"/>
<?php
}
?>
</select>
<select name="category">
<option value="" selected>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("muskilaasaan");
$category = "SELECT cat FROM category";
$query_result = mysql_query($category);
while($result = mysql_fetch_assoc($query_result))
{
?>
<option value = "<?php echo $result['cat']?>"><?php echo $result['cat']?></option>
<?php
}
?>
</select>
Changed to mysql_fetch_assoc and also you didn't put anything in the option tags, that would cause it to appear blank.
it does not help if you specify the connection string as a second argument in mysql_select_db() ? see here for an example: http://php.net/manual/de/function.mysql-select-db.php