Extract multiple values from a MySQL table into HTML - javascript

I want to get three values from a MYSQL table, and display them in a text area. I can get only one value. If it possible, I want to save this selector, because it is critical to my program.
JavaScript:
function getsteel() {
var material = document.getElementsByName("option");
if (material[3].checked == true) {
var g = document.getElementById("selector1");
var str = g.options[g.selectedIndex].value;
document.getElementById('kr').value = str;
}
}
HTML:
<td>k<sub>r</td></sub>
<td>
<input type="text" id="kr" disabled style="width:50px;">
</td>
<td>[MPa]</td>
PHP:
<?php
mysql_connect("localhost","root","");
mysql_select_db("db-user22777");
//query
$sql=mysql_query("SELECT * FROM steels ORDER BY id ASC");
if(mysql_num_rows($sql)){
$select= '<select id="selector1" disabled size="12">';
while($r=mysql_fetch_array($sql)){
$select.='<option value="'.$r['kr'].'">'.$r['Steelname'].' | '.$r['kr'].' [MPa]</option>';
}
}
$select.='</select>';
echo $select;
?>
Thanks for any help provided!

Related

On any select option display only last inserted record

I have a little problem. I have a simple select field and get options from the database when the user clicks on any option I get an input box with the name of the last inserted record from the database, and I need to display the input box with the name of what the user selected not the last record. Code is bellow:
<div class="col-md-6 mb-3">
<label>Odaberite dimenziju produkta</label>
<select class="select2" name="size_id[]" multiple="multiple" id="selectBox" onchange="changeFunc();">
<?php
$get_sizes = "select * from sizes";
$sizes = mysqli_query($con,$get_sizes);
while($row_size = mysqli_fetch_array($sizes)){
$size_id = $row_size['id_size'];
$size_name = $row_size['productSize'];
$i++;
echo "<option value=".$size_name.">".$size_name."</option>";
} ?>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12 mb-3">
<div id="textboxcont" style="display: inline-flex; width: 100%;"></div>
<script type="text/javascript">
function changeFunc() {
document.getElementById('textboxcont').innerHTML = '';
var selectBox = document.getElementById("selectBox");
var selectedValues = Array.from(document.getElementById('selectBox').selectedOptions).map(el=>el.value);
//alert(selectedValues)
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", "<?php echo $size_name; ?>");
i1.setAttribute("id", "<?php echo $size_name; ?>");
i1.setAttribute("placeholder", "Enter price for <?php echo $size_name; ?>");
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
}
</script>
</div>
I need when the user clicks on one of four available selected options to display selected inputs with different names. Now when users select any 1 or 2 or 3 available options they display only the last records from the database. Any help why?
You are having problem here..
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", "<?php echo $size_name; ?>");
i1.setAttribute("id", "<?php echo $size_name; ?>");
i1.setAttribute("placeholder", "Enter price for <?php echo $size_name; ?>");
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
Your $size_name var contains last value of the query data array that you looped already while adding options to the select.
You should not use that to set attribute while creating input.
You should use the values that you have collected in selectedValues.
You can either itarate through it or use array index like selectedValues[ i ] to set input attribute like below.
function changeFunc() {
document.getElementById('textboxcont').innerHTML = '';
var selectBox = document.getElementById("selectBox");
var selectedValues = Array.from(document.getElementById('selectBox').selectedOptions).map(el=>el.value);
//alert(selectedValues[0]);
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", selectedValues[i]);
i1.setAttribute("id", selectedValues[i]);
i1.setAttribute("placeholder", "Enter price for " + selectedValues[i] );
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
}

How to update each row of a dynamic PHP table

I am trying to change the quantity of each row based on the 'Amt' that is inputted in the last column of that row. It's a search table that's based off the Area #. Essentially I want the user to be able to input a location and move bulk items from the current area to the new area that was inputted. If the Amt would equal zero that row would be skipped and no update would take place. Otherwise it would create a new row in the database with the new data.
Link to screenshot
https://photos.google.com/photo/AF1QipP2HMqNFmv208VOOl2DvppPGiZkv7f_keD_f8tj
This is my php table code:
The values for country, region, location and placeid are stored in the dropdown.
<?php
if (isset($_GET['Placeid'])) {
$moveplace = $_GET['Placeid'];
$sql = "SELECT *
FROM Parts p, Locations l
WHERE Placeid = '$moveplace' and p.locationid = l.locationid";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
if ($i % 2 == 0) {
$bgcolor = "rgba(199, 199, 199, 0.3)";
} else {
$bgcolor = "rgba(199, 199, 199, 0.8)";
}
echo "<div>
<input type='hidden' value='".$row['id']."' name='hiddensearchid'>
<input type='hidden' value='".$row['PartDescription']."' name='movedesc'>
<input type='hidden' value='".$row['BrandName']."' name='moveBN'>
<input type='hidden' value='".$row['CategoryName']."' name='moveCN'>
<input type='hidden' value='".$row['NSN_number']."' name='moveNSN'>
<input type='hidden' value='".$row['Image']."' name='moveimage'>
<table class=searcht style='background-color:$bgcolor'>
<tbody>
<tr>
<td value='".$row['PartNum']."' name='movepart'>".$row['PartNum']."</td>
<td value='".$row['ModelNum']."' name='movemodelnum'>".$row['ModelNum']."</td>
<td>".$row['Country']."</td>
<td>".$row['Region']."</td>
<td>".$row['Location']."</td>
<td>".$row['Placeid']."</td>
<td style='width:100px' value='".$row['UnitNum']."' name='moveunitnum'>".$row['UnitNum']."</td>
<td style='width:50px;' value='".$row['QTY']."' name='moveqty'>".$row['QTY']."</td>
<th style='width:50px; border-right:none;'><input style='width:20px; text-align:center;' value='0' type=text name='moveamt'></th>
</tr>
</tbody>
</table>
</div>";
$i++;
}
echo "<tr><td></td><td><input class='submit' type='submit' value='Confirm' name='submitPlacemove' onclick=\"return confirm ('Are you sure you want to submit?')\"></td></tr></form>";
}
}
I figure I need to use some sort of JavaScript but I'm new to it. Any help is appreciated.
I assume there is a Done button that the user will press when ready to scan the table for changes and update the database.
read and store the current values of the table (before any user changes)
When Done button clicked, scan table row-by-row and compare stored value with current value
When find a change, send the data over to a PHP file whose job is to update the back-end table with the new data (Note: you will need to send both the new data AND an item id, so it knows where to put the new data)
Here is a very rough, untested, simple example of what the code might look like:
var arr_old = [];
var arr_new = [];
$.each( $('table tr'), function(i, v){
if (i==0) return true; //ignore header row (return true === continue)
let currval = $(this).find('td:nth-child(3) index').val();
arr_old.push(currval);
});
$('#btnDone').click(function(){
$.each( $('table tr'), function(i, v){
if (i==0) return true; //ignore header row (return true === continue)
let row_id = $(this).find('td:nth-child(1)').text(); //1 or 2 or ...
let newval = $(this).find('td:nth-child(3) index').val();
if ( newval !== arr_old[i+1] ){
$.ajax({
type = 'post',
url = 'path/to/your/php_file.php',
data = 'item_id=' +row_id+ '&new_val=' +newval
}).done(function(recd){
console.log('Updated row ' + recd);
});
}
});
table{border-collapse:collapse;}
th,td{border:1px solid #ccc;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table>
<tr><th>ID</th><th>Col 1</th><th>Edit Col</th></tr>
<tr><td>1</td><td>Summat</td><td><input class="bob" type="text" value="car" /></td></tr>
<tr><td>2</td><td>Other</td><td><input class="bob" type="text" value="bike" /></td></tr>
<tr><td>3</td><td>Summat</td><td><input class="bob" type="text" value="foot" /></td></tr>
</table>
<button id="btnDone">Done</button>
If you are new to javascript, I suggest using jQuery for these reasons
References:
update list with jquery & ajax
http://learn.jquery.com/about-jquery/how-jquery-works/
SLAKS jQuery Tutorial - Use right-arrow to display next bit of text

Ajax load() loads only once [duplicate]

This question already has answers here:
How do I attach events to dynamic HTML elements with jQuery? [duplicate]
(8 answers)
Closed 4 years ago.
I have a school project of making some page, which have to add, remove, modify and sort data from mysql. And i need, to refresh section 3 called "jezdci" or just the table in it. I using load() for that. But its loads only once, when i click on that a second time, nothing happend. Then i have to again refresh the page. And i need to load it again and again. Do someone know, where is a mistake?
You can see it at http://188.75.190.236/host/xhrazd7/www/ZP%20Hrazdira/index1.php
HTML:
<section>
<?php include "vypis.php"; ?>
</section>
JS:
$(document).ready(function(){
$(".serad > td").click(function(){
y = $(this).index();
$("section:eq(2)").load("vypis.php",{
serad:y
},);
alert("Loaded index of td on click with value: "+y);
});
});
PHP:
<?php
include "conn.php";
if(!empty($_POST["serad"])){
$serad = $_POST["serad"];
echo "<script>alert(\"variable succefully sended to PHP with value of \"+$serad);</script>";
}else{
$serad=8;
}
if($serad==0) $SQLprikaz = "SELECT * FROM ZP ORDER BY ID";
if($serad==1) $SQLprikaz = "SELECT * FROM ZP ORDER BY jmeno";
if($serad==2) $SQLprikaz = "SELECT * FROM ZP ORDER BY prijmeni";
if($serad==3) $SQLprikaz = "SELECT * FROM ZP ORDER BY vek";
if($serad==4) $SQLprikaz = "SELECT * FROM ZP ORDER BY bydliste";
if($serad==5) $SQLprikaz = "SELECT * FROM ZP ORDER BY ulice";
if($serad==6) $SQLprikaz = "SELECT * FROM ZP ORDER BY kategorie";
if($serad==7) $SQLprikaz = "SELECT * FROM ZP ORDER BY zaplaceno";
if($serad==8) $SQLprikaz = "SELECT * FROM ZP";
$result = $conn->query("$SQLprikaz");
echo "<table>";
echo"<tr class=\"serad\"> <td><p>Pořadí</p></td> <td><p>Jméno</p></td> <td><p>Příjmení</p></td> <td><p>Věk</p></td> <td><p>Bydliště</p></td> <td><p>Ulice</p></td> <td><p>Kategorie</p></td> <td><p>Zaplaceno</p></td> </tr>";
while($zaznam=$result->fetch_array(MYSQLI_NUM)){
echo"<tr> <td>$zaznam[0]</td> <td>$zaznam[1]</td> <td>$zaznam[2]</td> <td>$zaznam[3]</td> <td>$zaznam[4]</td> <td>$zaznam[5]</td> <td>$zaznam[6]</td> <td>$zaznam[7]</td> </tr>";
}
echo "</table>";
?>
And sorry for my poor english :D
PS: Když by se tu našel někdo hodný z Česka nebo Slovenska a měl chvíli času, budu rád, když mě zkontaktujete. Dík < some boring notes in my native language
and Thanks a lot!
As haï_uit mentioned it's because there's no event attached to the next table. You can get around this by targeting an element that will always be in the page and using the on Method like so:
$(document).ready(function(){
$("body").on("click", ".serad > td", function(){
y = $(this).index();
$("section:eq(2)").load("vypis.php",{
serad:y
},);
alert("Loaded index of td on click with value: "+y);
});
});
The problem is here :
$(document).ready(function(){
$(".serad > td").click(function(){
y = $(this).index();
$("section:eq(2)").load("vypis.php",{
serad:y
},);
alert("Loaded index of td on click with value: "+y);
});
});
After your ajax load successfully, your old table which has "td" attached to click event is replaced by new table which doesn't have "td" with click event. So in your ajax load function, you must add click event for your table again after it load successfully. Another solution is just replace the data rows, not the whole table.
First option, you can add the click event again :
$(document).ready(function(){
var tabs = $('.serad > td');
tabs.click(changeTabs);
function changeTabs() {
y = $(this).index();
$('section:eq(2)').load('vypis.php',{
serad:y
}, function () {
tabs = $('.serad > td');
tabs.click(changeTabs);
});
}
}
Second option, only load table content:
Change your html file to this :
<section>
<table>
<tbody id="tabs">
<tr class="serad">
<td>
<p>Pořadí</p>
</td>
<td>
<p>...</p>
</td>
</tr>
</tbody>
<tbody id="content">
<?php include "vypis.php"; ?>
</tbody>
</table>
</section>
in php file, only echo the rows :
while($zaznam=$result->fetch_array(MYSQLI_NUM)){
echo"<tr> <td>$zaznam[0]</td> <td>$zaznam[1]</td> <td>$zaznam[2]</td> <td>$zaznam[3]</td> <td>$zaznam[4]</td> <td>$zaznam[5]</td> <td>$zaznam[6]</td> <td>$zaznam[7]</td> </tr>";
}
and finally, in your script :
$(document).ready(function() {
$('.serad > td').click(function () {
y = $(this).index();
$.post('vypis.php', { serad: y }, function (response) {
$('#content').html(response);
});
});
});

Populate select box from database query based on another select box using only 1 table

Hi guys I am currently creating a website with the main function of booking cars. Therefore the user would be first able to select a car category from the database query which will output the selected car category names. After selecting the car category name, the second select box would then by dynamically updated with a new set of of car names that are associated with the category.
There may have been many similar questions to this however for the website NO jQuery or AJAX can be utilized. And other questions and examples often utilize 2 or more tables however I am using only 1 table for this function.
The example below should show how the Select box should be updated:
Dynamically updated select box.
The table utilized is this:
Table Utilized
My codes are as such:
<?php
session_start();
include "dbconn.php";
$query = "SELECT carid, brand FROM cars";
$result = $dbcnx->query($query);
while($row = $result->fetch_assoc()){
$subcats[] = array("id" => $row['carid'], "val" => $row['brand']);
}
$jsonSubCats = json_encode($subcats);
?>
<!docytpe html>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
</head>
<body onload='loadCategories()'>
Car Category:<br />
<select size="1" name="categoriesSelect" id="categoriesSelect">
<option> Select Car Category </option>
<option value="sedan"> Sedan </option>
<option value="mpv"> MPV </option>
<option value="hatch"> Hatchback </option>
</select><br /><br />
Car Brand:<br />
<select id='subcatsSelect'>
</select>
</body>
</html>
I may have identified the error to the php statement:
while($row = $result->fetch_assoc()){
$subcats[] = array("id" => $row['carid'], "val" => $row['brand']);
As I can only see the first select box query correctly consisting of the 3 car category of MPV, Sedan and Hatchback.
Currently the all the Car Brand name appears however the results do not correspond with the car category as shown in the database.
Thank You.
As both arrays in PHP follow the same pattern when created the json data will be similar also thus the method to traverse the data should follow that in loadCategories function - so perhaps this:
function updateSubCats(){
var oSelect = document.getElementById("subcatsSelect");
oSelect.options.length = 0;
for( var i in subcats ){
oSelect.options[ i ]=new Option( subcats[ i ].val, subcats[ i ].id );
}
}
Without using Ajax or over complicating things with complex json iteration you could try along these lines. It should be noted that embedding the $_GET variable directly in the sql is not the best option - prepared statements would be better but should give the idea.
<?php
session_start();
include "dbconn.php";
?>
<!docytpe html>
<html>
<head>
<title>Chained select</title>
<script type='text/javascript'>
function bindEvents(){
document.getElementById('categories').addEventListener( 'change', getSubcategories, false );
}
function getSubcategories(e){
var el=e.target ? e.target : e.srcElement;
var value=el.options[ el.options.selectedIndex ].value;
location.search='?category='+value;
}
document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<form>
<select id='categories'>
<?php
$query = "SELECT carcat FROM cars";
$result = $dbcnx->query($query);
while( $row = $result->fetch_assoc() ){
echo "<option value='{$cat['carcat']}'>{$cat['carcat']}";
}
?>
</select>
<select id='subcategories'>
<?php
if( !empty( $_GET['category'] ) ){
$sql = "SELECT carid, brand FROM cars where carcat='{$_GET['category']}';";
$result = $dbcnx->query( $sql );
if( $result ){
while( $row = $result->fetch_assoc() ){
echo "<option value='{$row['carid']}'>{$row['brand']}";
}
}
}
?>
</select>
</form>
</body>
</html>
Of course it won't, you're accessing your arrays wrong:
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
^^^^^ ^^^^^
Your subcats array is only 2-dimensional, yet you're accessing it as a 3-dimentional array here.

Display array of products one by one by brand

I have a code in which i want to display product list from array.
I am getting around 1000 products from an array of n number of brands.n can be 1,2,3..etc.
I want to display 2 products of one brand then 2 products from second brand and then 2 from next brand and so on it should be repeated while displaying..
Homepage.php
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
#image{
width:250px;
height:250px;
border:1px solid black;
}
</style>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="brand"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
function get_disc_value(){
var d_value=[];
$('input[name="discount"]:checked').each(function () {
d_value.push(this.value);
});
return d_value.join(',');
}
$(document).ready(function(){
checkboxValidate = function (e) {
if(e)e.preventDefault();
//alert("hi");
//var os = $('#originState').val();
//var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
var disc=get_disc_value();
//var queryString = "os=" + os;
var data = "?ser=" + ser;
var queryString = "&ser=" + ser;
// alert(ser);
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: {ser:ser,disc:disc},
dataType : 'html',
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
}
$( "[type=checkbox]" ).change(checkboxValidate);
checkboxValidate();
});
</script>
brand
<input type="checkbox" name="brand" value="Sunbaby" id="check" />Sunbaby
<br/>
<input type="checkbox" name="brand" value="Advance Baby" id="check"/>Advance Baby
<br/>
store
<br/>
<input type="checkbox" name="discount" value="10" />10
<br/>
<input type="checkbox" name="discount" value="20" />20
<br/>
<input type="checkbox" name="discount" value="30" />30
<br/>
<button id="btnSubmit">sort</button>
<div id="image">
<img src="http://img5a.flixcart.com/image/sunglass/4/u/y/mb-d4-09b-miami-blues-free-size-275x275-imadzkhuchryqjgp.jpeg" width="250px" height="250px"/>
</div>
<div id="results">
sdfsdfsdfsdfdsfgsdgsbsfgvf
</div>
</body>
</html>
sortingajax.php
<?php
include('connection.php');
$query=$_POST['ser'];
$query2=$_POST['disc'];
$query=explode(",",$query);
$query = array_filter($query);
$query2=explode(",",$query2);
$query2 = array_filter($query2);
$result=count($query);
$result1=count($query1);
//echo $result;
echo $query;
echo $query1;
echo $result1;
$parts = array();
$brandarray=array();
$discarray=array();
$limit = 10;
$offset = 0;
foreach( $query as $queryword ){
$brandarray[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
foreach( $query2 as $discword ){
$discarray[] = '`DPERCENT` < "'.$discword.'"';
}
"/>
I want to display 2 products of one brand first and then 2 from second one and then from next brands.But according to above code it displays all products from one brand and then from next brand....Please guide me on how to change above code product list brand by brand..
based on a quick overview of your code, you seem to be adding the first element from each product to the array and then the second and then the third etc.. until you reach the highest count.
try instead, first limiting the max to only 2 instead of the max (so in this case, $highest_number should =2)
and second, add 1 brand, then the next then the next, instead of all at once, as unless you are handling it some other way would interlace each of the brands. I dont know if thats what you want?
does this help?
I've spent a little time looking at your code and am not entirely sure how it works. It seems like there's got to be an easier way to do this. Can you start a counter and cut off your loops once it hits the counter?
$i = 0;
$all_products = array();
while($row = mysql_fetch_array($firstsql3)) {
if (++$i <= 2) {
// DO YOUR STUFF HERE
$product_name = $row['product_name']; // GET THE PRODUCT NAME FROM THE DB
$product_color = $row['product_color'];
$product_size = $row['product_size'];
$individual_product_array = array(); // CREATE A NEW ARRAY FOR THIS PRODUCT
$individual_product_array['color'] = $product_color;
$individual_product_array['size'] = $product_size;
$all_products[$product_name][] = $individual_product_array;
}
}
If you insert _POST vars in mysql queries like this you will be hacked immediately see :
'`BRAND` LIKE "%'.$queryword.'%"';

Categories

Resources