jcjst21 Posted November 15, 2011 Share Posted November 15, 2011 Hello, I have a script that displays that uses a while loop in php to display all of the records. For each record, I added an input text box with a button to update one of the fields in the record set. When I run the script only the first listing will update and the subsequent listings on the page will not update. Should I go about this set up differently? <html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <head> <?php session_start(); ?> <script language="JavaScript"> TargetDate = "11/18/2011 6:00 PM"; BackColor = "palegreen"; ForeColor = "navy"; CountActive = true; CountStepper = -1; LeadingZero = true; DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds."; FinishMessage = "It is finally here!"; </script> <script language="JavaScript" src="http://scripts.hashemian.com/js/countdown.js"></script> <!-- function timedRefresh(timeoutPeriod) { setTimeout("location.reload(true);",timeoutPeriod); } // --> <script type="text/JavaScript"> function showCurrentPrice(str,str1) { if (str=="") { document.getElementById("priceElement").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("priceElement").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getPrice.php?q="+str+"&s="+str1,true); xmlhttp.send(); } </script> <?php $con=mysql_connect("xxxx", "xxxx", "xxxx") or die ("cannot connect"); mysql_select_db("tab_test") or die ("cannot select database"); echo 'Welcome ' .$_SESSION['username']. '!'; echo '<br /><br /><br />'; echo '<a href="tab_logout.php">Sign Out</a>'; $result=mysql_query("SELECT treeID, treeName, treePicture, treeGiver, treeDesc, CurrentPrice FROM Trees ORDER BY treeName"); $treeID=$_POST['treeID']; $newPrice=$_POST['newBid']; $result2=mysql_query("UPDATE Trees SET CurrentPrice ='$newPrice' WHERE treeID = '$treeID'"); ?> </head> <body> <table> <tr> <td>Active Trees</td> </tr> </table> <?php while($row=mysql_fetch_array($result)) { $treeID=$row['treeID']; echo "<form>"; echo "<table>"; echo "<tr><td><img src=" .$row['treePicture']. "></td></tr>"; echo "<tr><td><input type=\"text\" name=\"treeID\" id=\"treeID\" value=\"" .$treeID. "\" /></td></tr>"; echo "<tr><td>Current Price: $" .$row['CurrentPrice']. "<div id=\"priceElement\"></div></td></tr>"; echo "<tr><td>New Bid: <input type=\"text\" id=\"newBid\" name=\"newBid\" \><button type=\"button\" name=\"bidNow\" value=\"Bid\" onclick=\"showCurrentPrice(document.getElementById('treeID').value,document.getElementById('newBid').value)\"></td></tr>"; echo "<tr><td>" .$row['treeName']. "</td></tr>"; echo "<tr><td>" .$row['treeGiver']. "</td></tr>"; echo "<tr><td>" .$row['treeDesc']. "</td></tr>"; echo "</table>"; echo "</form>"; } ?> </body> <?php mysql_close($con); ?> </html> Quote Link to comment https://forums.phpfreaks.com/topic/251211-help-with-php-while-loop-with-input-text-boxes/ Share on other sites More sharing options...
Psycho Posted November 15, 2011 Share Posted November 15, 2011 You have two input fields for each record 'treeID' and 'newBid'. But, you give the fields the same name for every record and only one value can be passed for a single 'name' - unless that name is an array. Plus, you are creating individual forms for each record. Do you want the user to only be able to update ONE record at a time or ALL of them? Looking further at your code, it makes no sense why you would make the ID field an editable input. You aren't letting them insert records and if you change the ID it wouldn't do anything. Quote Link to comment https://forums.phpfreaks.com/topic/251211-help-with-php-while-loop-with-input-text-boxes/#findComment-1288473 Share on other sites More sharing options...
jcjst21 Posted November 15, 2011 Author Share Posted November 15, 2011 I want the user to be able to choose which one they want to update. It's basically an online bidding area. Where they pick an item to bid on and then click the "bid" button. However, when I test out the input box; the first record that displays; it allows me to place a bid, but then when I enter a bid in another listing. The button does nothing. I tried making it a form, but that didn't work before, but i forgot to take out the tags. I do not want the id field to be able to be updated, however i was using that for testing purposes for my update script. So how should i make this where when the user clicks the button and the update for that particular record is done, it will then allow me to update another listing? Quote Link to comment https://forums.phpfreaks.com/topic/251211-help-with-php-while-loop-with-input-text-boxes/#findComment-1288489 Share on other sites More sharing options...
Psycho Posted November 15, 2011 Share Posted November 15, 2011 I see you are using AJAX - and there is nothing wrong with that. But, typically you only want JS to enhance the functionality of your page and not be a requirement of it. So, I would suggest making each record it's own form and use a submit button. Then once it works by using pure HTML, then you can implement JavaScript on top of the current code. Youwould do this by using the form's onsubmit trigger to run the javascript and then do a "return false" which would prevent the form from actually submitting. So, if the user doesn't have JS enabled the form will submit normally, if they have JS enabled then the data is processed via AJAX. Having said all that, the problem you are having is expressly due to 1) the fact that you are reusing names of elements and 2) the javascript is referencing the same elements. Here is some of your JS function: function showCurrentPrice(str,str1) { if (str=="") { document.getElementById("priceElement").innerHTML=""; return; } You used the id of 'priceElement' for all of your records - how is the javascript supposed to know which one you are referring to? There can only be one instance of an id on the page. OK, here is a significant rewrite of your code. I put things in a more logical order and tidied up some things. I've tested this and it works - without the AJAX enabled. I have included a comment next to where the opening form tag is defined that shows what you can put in the onsubmit trigger of the form to get the AJAX working. The revised code should also work for the AJAX, but I don't have the getPrice.php page to test <?php session_start(); $con = mysql_connect("localhost", "root", "") or die ("cannot connect"); mysql_select_db("tab_test") or die ("cannot select database"); //Parse input into SQL safe values $updateTreeID = (isset($_POST['treeID'])) ? intval($_POST['treeID']) : false; $bidAmt = (isset($_POST['newBid'])) ? floatval($_POST['newBid']) : false; //If input values were passed via POST, run update query if($updateTreeID && $bidAmt) { $query = "UPDATE Trees SET CurrentPrice ='$bidAmt' WHERE treeID = '$updateTreeID'"; $result = mysql_query($query); } //Create and run query to get all records to create bid forms $query = "SELECT treeID, treeName, treePicture, treeGiver, treeDesc, CurrentPrice FROM Trees ORDER BY treeName"; $result=mysql_query($query); //Create bid forms $forms = ''; while($row=mysql_fetch_assoc($result)) { $treeID = $row['treeID']; $price = '$' . number_format($row['CurrentPrice'], 2); // TO ENABLE AJAX : use onsubmit="submitBid(this); return false;" $forms .= "<form id=\"bid_{$treeID}\" onsubmit=\"\" action=\"\" method=\"post\">\n"; $forms .= "<table>\n"; $forms .= "<tr><td><img src=\"{$row['treePicture']}\"></td></tr>"; $forms .= "<tr><td><input type=\"text\" name=\"treeID\" id=\"treeID_{$treeID}\" value=\"{$treeID}\" /></td></tr>\n"; $forms .= "<tr><td>Current Price: {$price}<div id=\"priceElement_{$treeID}\"></div></td></tr>\n"; $forms .= "<tr><td>"; $forms .= "New Bid: <input type=\"text\" id=\"newBid_{$treeID}\" name=\"newBid\" \>"; $forms .= "<button type=\"submit\">Bid</button>"; $forms .= "</td></tr>\n"; $forms .= "<tr><td>{$row['treeName']}</td></tr>\n"; $forms .= "<tr><td>{$row['treeGiver']}</td></tr>\n"; $forms .= "<tr><td>{$row['treeDesc']}</td></tr>\n"; $forms .= "</table>\n"; $forms .= "</form>\n"; } mysql_close($con); ?> <html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <head> <script type="text/JavaScript"> TargetDate = "11/18/2011 6:00 PM"; BackColor = "palegreen"; ForeColor = "navy"; CountActive = true; CountStepper = -1; LeadingZero = true; DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds."; FinishMessage = "It is finally here!"; //function timedRefresh(timeoutPeriod) //{ // setTimeout("location.reload(true);",timeoutPeriod); //} function submitBid(formObj) { var treeID = formObj.id.substr(4); var bidAmt = formObj.elements['newBid_'+treeID].value; var priceDiv = formObj.elements['priceElement_'+treeID]; if (bidAmt=='') { priceDiv.innerHTML = ''; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { priceDiv.innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET", "getPrice.php?q="+bidAmt+"&s="+treeID,true); xmlhttp.send(); } </script> </head> <body> Welcome <?php echo $_SESSION['username']; ?>! <br /><br /><br /> <a href="tab_logout.php">Sign Out</a> <table> <tr> <td>Active Trees</td> </tr> </table> <?php echo $forms; ?> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/251211-help-with-php-while-loop-with-input-text-boxes/#findComment-1288519 Share on other sites More sharing options...
jcjst21 Posted November 17, 2011 Author Share Posted November 17, 2011 Thank you so much! So if I have an ajax request that continuously polls the server for price updates, like if another user bids on an item, and i want the price to automatically change... what parameter would i pass into that function? To refresh the page every 30 seconds or so? Quote Link to comment https://forums.phpfreaks.com/topic/251211-help-with-php-while-loop-with-input-text-boxes/#findComment-1288977 Share on other sites More sharing options...
Psycho Posted November 17, 2011 Share Posted November 17, 2011 OK, so you are wanting the price (via AJAX) to be updated based upon 'Other" users' bids. It looks like your original code was running the AJAX code when the user submitted their bid. So, what you want is a JavaScript timed event to poll the server every 30 seconds (but you could also update when the user places a bid). You do not want to refresh the page. Plus, do you want to update the prices for ALL the items on the page as other users place bids or do you only want to update the ones for which the current user has placed a bid? Quote Link to comment https://forums.phpfreaks.com/topic/251211-help-with-php-while-loop-with-input-text-boxes/#findComment-1289013 Share on other sites More sharing options...
Psycho Posted November 17, 2011 Share Posted November 17, 2011 OK, this is VERY rough code, but it should work for what you are trying to achieve. Bid Page <?php session_start(); $con = mysql_connect("localhost", "root", "") or die ("cannot connect"); mysql_select_db("tab_test") or die ("cannot select database"); //Parse input into SQL safe values $updateTreeID = (isset($_POST['treeID'])) ? intval($_POST['treeID']) : false; $bidAmt = (isset($_POST['newBid'])) ? floatval($_POST['newBid']) : false; //If input values were passed via POST, run update query $response = ''; if($updateTreeID && $bidAmt) { $query = "UPDATE Trees SET CurrentPrice = '$bidAmt' WHERE treeID = '$updateTreeID' AND CurrentPrice < '$bidAmt'"; $result = mysql_query($query); if(mysql_affected_rows()) { $response = "You are now the high bidder"; } else { $response = "You have been outbid"; } } //Create and run query to get all records to create bid forms $query = "SELECT treeID, treeName, treePicture, treeGiver, treeDesc, CurrentPrice FROM Trees ORDER BY treeName"; $result=mysql_query($query); //Create bid forms $forms = ''; while($row=mysql_fetch_assoc($result)) { $treeID = $row['treeID']; $price = '$' . number_format($row['CurrentPrice'], 2); $forms .= "<form id=\"bid_{$treeID}\" onsubmit=\"\" action=\"\" method=\"post\">\n"; $forms .= "<table>\n"; $forms .= "<tr><td><img src=\"{$row['treePicture']}\"></td></tr>"; $forms .= "<tr><td><input type=\"text\" name=\"treeID\" id=\"treeID_{$treeID}\" value=\"{$treeID}\" /></td></tr>\n"; $forms .= "<tr><td>Current Price: <span id=\"priceElement_{$treeID}\">{$price}</span></td></tr>\n"; $forms .= "<tr><td>"; $forms .= "New Bid: <input type=\"text\" id=\"newBid_{$treeID}\" name=\"newBid\" \>"; $forms .= "<button type=\"submit\">Bid</button>"; $forms .= "</td></tr>\n"; $forms .= "<tr><td>{$row['treeName']}</td></tr>\n"; $forms .= "<tr><td>{$row['treeGiver']}</td></tr>\n"; $forms .= "<tr><td>{$row['treeDesc']}</td></tr>\n"; $forms .= "</table>\n"; $forms .= "</form>\n"; } mysql_close($con); ?> <html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <head> <script type="text/JavaScript"> TargetDate = "11/18/2011 6:00 PM"; BackColor = "palegreen"; ForeColor = "navy"; CountActive = true; CountStepper = -1; LeadingZero = true; DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds."; FinishMessage = "It is finally here!"; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari var xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var prices = xmlhttp.responseText.split('|'); for(i=0; i<prices.length; i++) { price = prices[i].split(':'); document.getElementById('priceElement_'+price[0]).innerHTML = '$'+price[1]; } } } function updatePrices() { xmlhttp.open("GET", "getPrices.php", true); xmlhttp.send(); setTimeout('updatePrices()', 5000); } </script> </head> <body onload="updatePrices()"> Welcome <?php echo $_SESSION['username']; ?>! <br /><br /> <?php echo $response; ?> <br /><br /> <a href="tab_logout.php">Sign Out</a> <table> <tr> <td>Active Trees</td> </tr> </table> <?php echo $forms; ?> </body> </html> getPrices.php page (for the AJAX) <?php $con = mysql_connect("localhost", "root", "") or die ("cannot connect"); mysql_select_db("tab_test") or die ("cannot select database"); $query = "SELECT treeID, CurrentPrice FROM Trees"; $result=mysql_query($query); $outputAry = array(); while($row=mysql_fetch_assoc($result)) { $outputAry[] = "{$row['treeID']}:{$row['CurrentPrice']}"; } $outputStr = implode('|', $outputAry); echo $outputStr; ?> Quote Link to comment https://forums.phpfreaks.com/topic/251211-help-with-php-while-loop-with-input-text-boxes/#findComment-1289027 Share on other sites More sharing options...
jcjst21 Posted November 22, 2011 Author Share Posted November 22, 2011 Thank you very much. This worked out very nicely. It is exactly what i was looking for. Quote Link to comment https://forums.phpfreaks.com/topic/251211-help-with-php-while-loop-with-input-text-boxes/#findComment-1290607 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.