Jump to content

Help with PHP while loop with input text boxes


jcjst21

Recommended Posts

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>

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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?

 

 

Link to comment
Share on other sites

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>

Link to comment
Share on other sites

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?

 

 

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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;
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.