Creating a loop in Javascript based on php variable - javascript

Let us say I have the following script, calculating a sum.
Here is the code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript">
function updatesum() {
line1 = ((document.form.price_1.value -0) * (document.form.number_1.value -0));
line2 = ((document.form.price_2.value -0) * (document.form.number_2.value -0));
line3 = ((document.form.price_3.value -0) * (document.form.number_3.value -0));
line4 = ((document.form.price_4.value -0) * (document.form.number_4.value -0));
line5 = ((document.form.price_5.value -0) * (document.form.number_5.value -0));
document.form.sum.value = line1 + line2 + line3 + line4 + line5;
}
</script>
</head>
<body>
<?php
$tR = 1;
$maxlines = 5;
echo '<form name="form" method="post" action="action.php">';
echo '<table><tbody>';
while($tR <= $maxlines)
{
echo '<tr>';
echo '<td width="1"><input name="price_' . $tR . '" onChange="updatesum();" type="text"></td>';
echo '<td width="1"> x </td>';
echo '<td width="1"><input name="number_' . $tR . '" onChange="updatesum();" type="text" value="1"></td>';
echo '</tr>';
++$tR;
}
echo '</tbody></table>';
echo 'Total: <input name="sum" value="0" type="text" readonly="readonly">';
echo '<button type="submit" name="Submit" style="display: hidden;">Submit</button>';
echo '</form>';
?>
</body>
</html>
And that's fine... But now i change the variable $maxlines from 5 to 500...
How do I adjust the Javascript, without having to write something like:
function updatesum() {
line1 = ((document.form.price_1.value -0) * (document.form.number_1.value -0));
line2 = ((document.form.price_2.value -0) * (document.form.number_2.value -0));
line3 = ((document.form.price_3.value -0) * (document.form.number_3.value -0));
line4 = ((document.form.price_4.value -0) * (document.form.number_4.value -0));
line5 = ((document.form.price_5.value -0) * (document.form.number_5.value -0));
line6 = ((document.form.price_6.value -0) * (document.form.number_6.value -0));
.......................
line500 = ((document.form.price_500.value -0) * (document.form.number_500.value -0));
document.form.sum.value = line1 + line2 + line3 + line4 + line5 + line6 ........... + line500;
}

You can use a loop to go through all the fields:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript">
function updatesum() {
var prices = document.getElementsByName('price');
var numbers = document.getElementsByName('number');
var sum = 0;
for (var i = 0; i < prices.length; i++) {
sum += prices[i].value * numbers[i].value;
}
document.form.sum.value = sum;
}
</script>
</head>
<body>
<?php
$tR = 1;
$maxlines = 50;
echo '<form name="form" method="post" action="action.php">';
echo '<table><tbody>';
while($tR <= $maxlines)
{
echo '<tr>';
echo '<td width="1"><input name="price" onChange="updatesum();" type="text"></td>';
echo '<td width="1"> x </td>';
echo '<td width="1"><input name="number" onChange="updatesum();" type="text" value="1"></td>';
echo '</tr>';
++$tR;
}
echo '</tbody></table>';
echo 'Total: <input name="sum" value="0" type="text" readonly="readonly">';
echo '<button type="submit" name="Submit" style="display: hidden;">Submit</button>';
echo '</form>';
?>
</body>
</html>

You can easily transfer php variables to javascript like this
<script>
var maxlines = <?php echo $maxLines?>;
</script>
You now have a javascript variable maxlines equal to your php variable
Also, remember if you are transferring a string to put it in quotations
<script>
var myString = '<?php echo $myString?>';
</script>

The short version would be to update the script and have a loop there that does all this.
BUT (and a huge but that is)
There are a few things you can improve in your script, other than the solution itself.
You can try a different approach to your issue:
You don't have to bind a function to each input change element separately, and using onchange attributes in HTML is a little outdated method.
You don't have to define each line. You can sum them all up using JavaScript, without knowing how many of them you have.
I would rename your input elements name attribute into something you could work with in PHP, without knowing its size beforehand. For example, if you change the name of the attributes to name="price[]" and name="number[]", your values will magically be sent to your PHP script as $_POST["price"] and $_POST["number"]. From there, you can play with it dynammicaly.
And now to some real code:
By building the HTML as I've explained, you will end up with something following this idea:
<form name="form">
<input type="text" name="price[]" value="1" /><input type="text" name="number[]" value="10" /><br />
<input type="text" name="price[]" value="2" /><input type="text" name="number[]" value="20" /><br />
<input type="text" name="price[]" value="3" /><input type="text" name="number[]" value="30" /><br />
<input type="text" name="price[]" value="4" /><input type="text" name="number[]" value="40" /><br />
<br /><input type="text" name="sum" value="0" id="sum" />
</form>
And then, following the event binding techniques I suggested, your JavaScript will be simplified to something like this:
function updateSum() {
var prices = document.getElementsByName("price[]");
var numbers = document.getElementsByName("number[]");
var sum = 0;
for (var i=0; i < prices.length; i++) {
sum += prices[i].value * numbers[i].value;
}
document.getElementById("sum").value = sum;
}
var prices = document.getElementsByName("price[]");
var numbers = document.getElementsByName("number[]");
for (var i=0; i < prices.length; i++) {
prices[i].addEventListener('change', updateSum, false);
numbers[i].addEventListener('change', updateSum, false);
}
I've created a jsFiddle (http://jsfiddle.net/nXqgW/2/) showing this code in action.

You can use the code like that:
<script>
function updatesum() {
<?php $lines = array() ?>
<?php for($i = 0; $i < $count; $i++) : ?>
line<?= $i ?> = ((document.form.price_<?= $i ?>.value -0) * (document.form.number_<?= $i ?>.value -0));
<?php $lines[] = 'line' . $i;
<?php endfor; ?>
document.form.sum.value = <?= implode(' + ', $lines);
}
</script>

You need to output the javascript lines with PHP, so in PHP where you have your maxlines variables you can do a loop like;
<script>
...
<?php for($i = 0; $i < $maxlines; $i++) {
//Output javascript line
?>
line<?php echo $i; ?> = ((document.form.price_<?php echo $i; ?>.value -0) * (document.form.number_<?php echo $i; ?>.value -0));
<?php
} ?>
document.form.sum.value = 0 <?php for($int i = 0; $i < $maxlines; $i++) {
echo '+ line' . $i;
} ?>
</script>
I haven't tested this code, but it should work.

Related

How can put my values to mysql from my php table with jquery ajax method

<div id="kutu">
<?php
echo "<table ' border='1' width='200px'>";
echo "<tr>";
echo "<th>#</th>";
echo "<th>Oyuncu Adi</th>";
echo "</tr>";
for ($x = 1; $x <= $playernum; $x++) {
echo "<tr>";
echo "<td>$x </td>";
echo "<td><input id='serdar' type='text' name='player$x' > </td>";
echo "</tr>";
}
echo "</table>";
?>
<p> <input type="submit" value="Kayit Et!"></p>
</div>
Im taking $playernum from other page. In this table I will take players name and I wanna put this names to my mysql db with javascript ajax method. But I couldnt find the way.
My table looks like:
I suggest you change your input-text to the same name like this, instead of player$x:
<form method="POST">
<input type="text" name="player" /><br />
<input type="text" name="player" /><br />
<input type="text" name="player" /><br />
<input type="text" name="player" />
<p id="result"></p>
<button id="btn">Get Player Names</button>
</form>
For the javascript:
<script>
$("form").submit(function(e) {
e.preventDefault();
players = document.getElementsByName("player");
var result = [];
for (var i = 0; i < players.length; i++) {
result[i] = players[i].value;
}
$.post(
'index.php', {
data: result
},
function(msg) {
document.getElementById("result").innerHTML = msg;
}
);
});
</script>
I just created an empty array and stored the values of each input into it. Then sent that array over to the PHP file.
For the index.php file:
$data = $_POST["data"];
echo "From PHP<br/>";
foreach ($data as $d){
echo $d . "<br/>";
}
So you can use the variable $d to access individual player names.
Result image

How to update quantity of database from php action

I am building a database of different devices which is displayed in a page which sells medical devices. When a user adds a quantity of the device to the cart, I want the database to be updated with (stock - quantity in cart) I am trying to do this on PHP but am having no luck. My attempt and code is below.
Here is a snippet of my attempt. I'm not sure where to place this in the code below.
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
if(isset($_POST['incqty'])){
$value += 1;
$query = "UPDATE products SET stock= (stock-$product_qty) WHERE product_name=$product_name";
mysql_select_db('products');
$retval = mysql_query($query,$mysqli);
}
?>
This is code for index.php
<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 align="center">Products </h1>
<!-- View Cart Box Start -->
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
echo '<div class="cart-view-table-front" id="view-cart">';
echo '<h3>Your Shopping Cart</h3>';
echo '<form method="post" action="cart_update.php">';
echo '<table width="100%" cellpadding="6" cellspacing="0">';
echo '<tbody>';
$total =0;
$b = 0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /> Remove</td>';
echo '</tr>';
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
echo '<td colspan="4">';
echo '<button type="submit">Update</button>Checkout';
echo '</td>';
echo '</tbody>';
echo '</table>';
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
?>
<!-- View Cart Box End -->
<!-- Products List Start -->
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price, stock FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<li class="product">
<form method="post" action="cart_update.php">
<div class="product-content"><h3>{$obj->product_name}</h3>
<div class="product-thumb"><img src="images/{$obj->product_img_name}"></div>
<div class="product-desc">{$obj->product_desc}</div>
<div class="product-info">
Price {$currency}{$obj->price}
<fieldset>
<label>
<span>Color</span>
<select name="product_color">
<option value="Black">Black</option>
<option value="Silver">Silver</option>
</select>
</label>
<label>
<span>Quantity</span>
<input type="text" size="2" maxlength="2" name="product_qty" value="1" />
</label>
</fieldset>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<div align="center"><button type="submit" id="updateb" class="add_to_cart">Add</button></div>
</div></div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
<!-- Products List End -->
</body>
</html>
This is code for cart_update.php
<?php
session_start();
include_once("config.php");
//add product to session or create new one
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0)
{
foreach($_POST as $key => $value){ //add all post vars to new_product array
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
//remove unecessary vars
unset($new_product['type']);
unset($new_product['return_url']);
//we need to get product name and price from database.
$statement = $mysqli->prepare("SELECT product_name, price, stock FROM products WHERE product_code=? LIMIT 1");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $price, $stock);
while($statement->fetch()){
//fetch product name, price from db and add to new_product array
$new_product["product_name"] = $product_name;
$new_product["product_price"] = $price;
$new_product["product_stock"] = $stock;
if(isset($_SESSION["cart_products"])){ //if session var already exist
if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check item exist in products array
{
unset($_SESSION["cart_products"][$new_product['product_code']]); //unset old array item
}
}
$_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item
}
}
//update or remove items
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
//update item quantity in product session
if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){
foreach($_POST["product_qty"] as $key => $value){
if(is_numeric($value)){
$_SESSION["cart_products"][$key]["product_qty"] = $value; //change
}
}
}
//remove an item from product session
if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){
foreach($_POST["remove_code"] as $key){
unset($_SESSION["cart_products"][$key]);
}
}
}
//back to return url
$return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url
header('Location:'.$return_url);
?>
This is code for view_cart.php
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<h1 align="center">View Cart</h1>
<div class="cart-view-table-back">
<form method="post" action="cart_update.php">
<table width="100%" cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>Price</th><th>Total</th><th>Remove</th></tr></thead>
<tbody>
<?php
if(isset($_SESSION["cart_products"])) //check session var
{
$total = 0; //set initial total value
$b = 0; //var for zebra stripe table
foreach ($_SESSION["cart_products"] as $cart_itm)
{
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$subtotal = ($product_price * $product_qty); //calculate Price x Qty
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td>'.$currency.$product_price.'</td>';
echo '<td>'.$currency.$subtotal.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
echo '</tr>';
$total = ($total + $subtotal); //add subtotal to total var
}
$grand_total = $total + $shipping_cost; //grand total including shipping cost
foreach($taxes as $key => $value){ //list and calculate all taxes in array
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount; //add tax val to grand total
}
$list_tax = '';
foreach($tax_item as $key => $value){ //List all taxes
$list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
}
$shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
}
?>
<tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
<tr><td colspan="5">Add More Items<button type="submit">Update</button></td></tr>
</tbody>
</table>
<input type="hidden" name="return_url" value="<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
</div>
</body>
</html>
your variables $product_qty and $product_name are not defined and in the query pass the product name in the quotes as your query is in double quotes so pass name in the single quotes.
Also it will be better if you update using primary id not by name.

php information not passing through with sessions and pagination

So I've been looking at this page for hours and hours and I can't seem to figure out what the problem is here. I had this issues with all links previously, where I would lick a link to filter/sort database results, click a page link to go to the next page and it would display the second page without any filtered results. I resolved this for "Most Wins", "Best Save %" and "Best Goals Against" by the use of sessions, but for some reason it is still doing this when I try and filter results via my range sliders form. It works when I adjust the sliders, and submit, but if I click another page, once again, it show all results in the database. Can anyone see as to why it might be doing this? I've tried both post and get methods from the form but it didn't seem to work, but if anyone could provide some advice I would greatly appreciate it!!
Here is the code:
<body>
<header>
<div class="header-container">
<nav>
<img src="images/header_img.png" alt="Golaie Gear Online"/>
<ul>
<li>Browse Goalies</li>
<li>Browse Gear</li>
<li>Admin</li>
</ul>
<form method="get" action="<?php echo "generalsearch.php?q=$searchvalue"; ?>" class="search-field">
<input name="search" type="text" placeholder="Search">
<button type="submit" title="Search" id="submit"><img src="images/header_srch.png" alt="search"/></button>
</form>
</nav>
</div>
<div style="clear:both;"></div>
</header>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<style type="text/css">
#win-range, #gaa-range, #sv-range{
width: 160px;
font-size: 10px;
margin: 0 auto;
}
#win-range a, #gaa-range a, #sv-range a{
margin-top: 0px !important;
padding: 0 !important;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function(){
$("#win-range").slider({
range: true,
min: 1,
max: 1000,
values: [1, 1000],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#minwins").val(ui.values[0]);
$("#maxwins").val(ui.values[1]);
$("#winamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#winamount").val($("#win-range").slider("values", 0) + " - " + $("#win-range").slider("values", 1));
});
$(function(){
$("#gaa-range").slider({
range: true,
min: 0,
max: 10,
values: [0, 10],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#mingaa").val(ui.values[0]);
$("#maxgaa").val(ui.values[1]);
$("#gaaamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#gaaamount").val($("#gaa-range").slider("values", 0) + " - " + $("#gaa-range").slider("values", 1));
});
$(function(){
$("#sv-range").slider({
range: true,
min: 750,
max: 1000,
values: [750, 1000],
slide: function(event, ui) {
// in order to pass the user selected values to your app, we will use jQuery to prepopulate certain hidden form elements, then grab those values from the $_POST
$("#minsv").val(ui.values[0]);
$("#maxsv").val(ui.values[1]);
$("#svamount").val(ui.values[0] + " - " + ui.values[1]);
}
});
$("#svamount").val($("#sv-range").slider("values", 0) + " - " + $("#sv-range").slider("values", 1));
});
</script>
<?php
include("includes/header.php");
include("includes/mysqli_connect.php");
$sortDesc = $_REQUEST['sortstats'];
$sortAsc = $_REQUEST['sortstatslow'];
$minwins = $_GET['minwins'];
$maxwins = $_GET['maxwins'];
$mingaa = $_GET['mingaa'];
$maxgaa = $_GET['maxgaa'];
$minsv = $_GET['minsv'];
$maxsv = $_GET['maxsv'];
// FILTERING YOUR DB
$sortstats = $_GET['sortstats'];
$sortstatslow = $_GET['sortstatslow'];
$getminwins = $_REQUEST['getminwins'];
$getmaxwins = $_REQUEST['getmaxwins'];
$getmingaa = $_REQUEST['getmingaa'];
$getmaxgaa = $_REQUEST['getmaxgaa'];
$getminsv = $_REQUEST['getminsv'];
$getmaxsv = $_REQUEST['getmaxsv'];
// paging
$getcount = mysqli_query ($con,"SELECT COUNT(*) FROM Player");
$postnum = mysqli_result($getcount,0);// this needs a fix for MySQLi upgrade; see custom function below
$limit = 6; //how many blog posts per page you will see.
if($postnum > $limit){
$tagend = round($postnum % $limit,0);
$splits = round(($postnum - $tagend)/$limit,0);
if($tagend == 0){
$num_pages = $splits;
}else{
$num_pages = $splits + 1;
}
if(isset($_GET['pg'])){
$pg = $_GET['pg'];
}else{
$pg = 1;
}
$startpos = ($pg*$limit)-$limit;
$limstring = "LIMIT $startpos,$limit";
}else{
$limstring = "LIMIT 0,$limit";
}
// MySQLi upgrade: we need this for mysql_result() equivalent
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}
?>
<div class="listingcontainer">
<div class="sidebar">
<h3>Sort By:</h3>
Most Wins
Best Goals Against
Best Save %
<hr/>
<h3>Custom Filter</h3>
<br/>
<div class="custom-filter">
<form name="filters" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get" id="filters">
<label for="winamount">Win Range:</label>
<input type="text" id="winamount" />
<div style="clear:both;"></div>
<input type="hidden" id="minwins" name="minwins" value="0" />
<input type="hidden" id="maxwins" name="maxwins" value="1000" />
<div id="win-range"></div>
<br/>
<label for="gaaamount">GAA:</label>
<input type="text" id="gaaamount" /><br />
<div style="clear:both;"></div>
<input type="hidden" id="mingaa" name="mingaa" value="0" />
<input type="hidden" id="maxgaa" name="maxgaa" value="10" />
<div id="gaa-range"></div>
<br/>
<label for="svamount">SV %:</label>
<input type="text" id="svamount" /><br />
<div style="clear:both;"></div>
<input type="hidden" id="minsv" name="minsv" value="750" />
<input type="hidden" id="maxsv" name="maxsv" value="1000" />
<div id="sv-range"></div>
<input type="submit" name="submit" id="submit"/>
</form>
</div>
</div>
<div class="main-listings">
<h1>Current NHL Goaltenders</h1>
<?php
session_start();
if($_SESSION['allresults'])
{
$result = mysqli_query($con, "SELECT * FROM Player ORDER BY PlayerID ASC $limstring");
if(isset($sortstats)){//THIS WORKS
session_start();
$_SESSION['sortStatsDesc'] = session_id();
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstats DESC $limstring ");
$filter = "sortstats={$sortDesc}";
}
if(isset($sortstatslow)) {//THIS WORKS
session_start();
$_SESSION['sortStatsAsc'] = session_id();
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstatslow ASC $limstring ");
$filter = "sortstatslow={$sortAsc}";
}
if(isset($minwins) || isset($maxwins) || isset($mingaa) || isset($maxgaa) || isset($minsv) || isset($maxsv))//THIS SEEMS TO WORK
{
session_start();
$_SESSION['customFilter'] = session_id();
$result = mysqli_query($con, "SELECT * FROM Player WHERE Wins BETWEEN '$minwins' AND '$maxwins' AND
GAA BETWEEN '$mingaa' AND '$maxgaa' AND SavePerc BETWEEN '$minsv' AND '$maxsv'
ORDER BY PlayerID ASC $limstring") or die (mysql_error());
$filter = "getminwins={$minwins}&getmaxwins={$maxwins}&getmingaa={$mingaa}&getminsv={$minsv}&getmaxsv={$maxsv}";
}
}
else if($_SESSION['sortStatsDesc'])//THIS WORKS
{
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstats DESC $limstring ");
}
else if($_SESSION['sortStatsAsc'])//THIS WORKS
{
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY $sortstatslow ASC $limstring ");
}
else if($_SESSION['customFilter'])//DON'T KNOW IF THIS IS DOING ANYTHING
{
$result = mysqli_query($con, "SELECT * FROM Player WHERE Wins BETWEEN '$getminwins' AND '$getmaxwins' AND
GAA BETWEEN '$getmingaa' AND '$getmaxgaa' AND SavePerc BETWEEN '$getminsv' AND '$getmaxsv'
ORDER BY PlayerID ASC $limstring");
}
else{
}
while($row = mysqli_fetch_array($result)){
$name = $row['LastName'] . ", " . $row['FirstName'];
$wins = $row['Wins'];
$pid = $row['PlayerID'];
$image = $row['Picture'];
$gaa = $row['GAA'];
$sv = $row['SavePerc'];
echo "<div class=\"player-listing\">";
echo "<div class=\"image-holder\">";
echo "<span class=\"helper\"></span>";
echo "<img src=\"admin/thumbs/$image\" alt=\"$name\">";
echo "</div>";
echo "<div style=\"clear:both;\"></div>";
echo "$name";
echo "<table align=\"center\">";
echo "<tr>";
echo "<td style=\"border-bottom: 1px solid #212121;\">Wins</td>";
echo "<td style=\"border-bottom: 1px solid #212121;\">GAA</td>";
echo "<td style=\"border-bottom: 1px solid #212121;\">SV%</td>";
echo "</tr>";
echo "<tr>";
echo "<td>$wins</td>";
echo "<td>$gaa</td>";
echo "<td>.$sv</td>";
echo "</tr>";
echo "</table>";
echo "</div>";
}
// paging links:
echo "<div class=\"paging\">";
if($postnum > $limit){
echo "<span class=\"page-numbers\"><strong>Pages:</strong> </span>";
$n = $pg + 1;
$p = $pg - 1;
$thisroot = $_SERVER['PHP_SELF'];
if($pg > 1){
echo "<< prev ";
}
for($i=1; $i<=$num_pages; $i++){
if($i!= $pg){
echo "$i ";
}else{
echo "$i ";
}
}
if($pg < $num_pages){
// INSERT QUERY STRING VARIBLE TO CARRY OVER DB QUERY
echo "next >>";
}
echo " ";
}
// end paging
echo "</div>";
?>
<br/>
</div>
<div style="clear:both;"></div>
</div>
EDIT: I fixed the paging issue by adding this into my code:
$getcount = mysqli_query ($con,"SELECT COUNT(*) FROM Player");
if($_SESSION['customFilter']){
$getcount = mysqli_query ($con,"SELECT COUNT(*) FROM Player WHERE Wins BETWEEN '$minwins' AND '$maxwins' AND
GAA BETWEEN '$mingaa' AND '$maxgaa' AND SavePerc BETWEEN '$minsv' AND '$maxsv'");
}
But it's still giving me grief when I click next page. I don't think the filter values are carryying over for some reason.
Remove all the existing session_start() and add one on the first rule of the page, like:
<?php
session_start();
?>
//Your html/js/php
...
...
For session to works the very first instruction you have to call is "session_start()". You should call it only once and at the very beginning of your script.
<?php session_start() ?>
// rest of code PHP/HTML/JS/CSS/anything

I want to sum the looped textbox

Hi guys I am new to javascript and php and I have a problem
I'd like to sum the looped text box but I am lack at logics
here is the code
<form name="rec" action="this.php" method="post" >
<?php
$x = 0;
while($x<=5){
$x++;
echo "<input type='text' name='n". $x."' id='n". $x."'>< input type='text' name='y". $x."' id='y". $x."'>
<input type='text' name='res". $x."' id='res". $x."'>";
}
?>
<input type="button" value="Compute" onclicked="compute()">
</form>
< script >
ctr = 0<
while(ctr<=5){
ctr++;
x = Number(document.getElementById("n"+ctr).value)
y = Number(document.getElementById("y"+ctr).value)
ans = x+y;
document.getElementById("res"+ctr).value = ans;
}
< /script>
I would like to get the out put of like this
Thank you I am not really specific :D
try this
<form name="rec" action="#" method="post">
<?php
$x = 0;
while($x<=5){
$x++;
echo "<input type='text' name='n". $x."' id='n". $x."'><input type='text' name='y". $x."' id='y". $x."'>
<input type='text' name='res". $x."' id='res". $x."'><br>";
}
?>
<input type="button" value="Compute" onclick="compute()">
</form>
<script>
function compute()
{
var ctr = 0;
while(ctr<=5){
ctr++;
var x = Number(document.getElementById("n"+ctr).value);
var y = Number(document.getElementById("y"+ctr).value);
var ans = x+y;
document.getElementById("res"+ctr).value = ans;
}
}
</script>
Where is your compute function? You should enclose the contents of the <script> tag with function compute().

dyninamicly extendable form

Ok maybe I've overlooked something really simple here, but I can't seem to figure this out. I am trying to make my form dynamicly extendable.
My Problem is i can't get this code working:
<html>
<head>
<?php
$i = 1;
$p = 1;
$r = 1;
?>
<script language="javascript">
function add()
{
document.getElementById("groesse").innerHTML = document.getElementById("grosse").innerHTML+"<input type='text' name='groesse[<?php echo $i;?>]'>";
document.getElementById("preis_l").innerHTML = document.getElementById("preis_l").innerHTML+"<input type='text' name='preis_a[<?php echo $p;?>]'>";
document.getElementById("preis_a").innerHTML = document.getElementById("preis_a").innerHTML+"<input type='text' name='preis_l [<?php echo $r;?>]'><br>";
<?php
$i = $i + 1;
$p = $p + 1;
$r = $r + 1;
?>
}
</script>
</head>
<body>
<?php
if ($_REQUEST['Selected'] == 'Speisekarte')
{
echo '<br><br><br><br>';
echo '<input type="button" value="+" onClick="add()">';
echo '<form action="insert.php" method="submit">';
echo '<table border="1">';
echo '<tr><td>ID</td><td>Name</td><td>Beschreibung</td><td>Größe</td><td>Preis_L</td><td>Preis_A</td></tr>';
echo '<tr><td><input type="text" id="ID" name="ID"></td>';
echo '<td><input type="text" id="Name" name="Name"></td>';
echo '<td><input type="text" id="Beschreibung" name="Beschreibung"></td>';
echo '<td id="groesse"></td>';
echo '<td id="preis_l"></td>';
echo '<td id="preis_a"></td>';
echo '</tr></table><input type="hidden" value="Speisekarte">';
echo '<button type="submit">OK</button></form>';
}
?>
</body>
</html>
I want when someone klicks the +-Button my Form gets 3 Textfields more in the table with the specific ids. I also tried it with div-Tags but that didn't worked too.
I hope someone can help me.
You can't use php clientside, it is parsed on the server only when visitor requests the page by GET or POST, so using $i = $i + 1 will not work clientside. By the way, use $i++ instead.
You could solve this with only javascript or, as an alternative, submit the form and present the form again with the extra fields needed so you can do it with php.
I recommend you have a look at jQuery and check out this answer with demo:
How to use jQuery to add form elements dynamically
(credits to PSL)

Categories