Jump to content

Variable variables in PHP 4.2+


colickyboy

Recommended Posts

As a noob PHP coder, I used to get by with variable variables but the security change in PHP 4.2 has made it much more difficult for noobs like me to do what we used to be able to do.

I'm trying to create a form where I can input stats for 15 players of a softball team and then post it to a db. I used variable variables in order to use a loop for both creating the form and posting to the db.

The code I'm working with is currently:

[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]<html>
<head><link rel="stylesheet" type="text/css" href="../styles/index.css"></head>
<body>
<table>
<tr>
<td width="740" id="maincontent">
<div><br>

<?php

//open database
$db=mysql_connect ("localhost", "user", "pw")
or die ('I cannot connect to the database because: ' .
mysql_error());
mysql_select_db("softball",$db);

if ($_POST['submit']) {

// update players' stats

$count = $_POST['count'];

for ($i = 1; $i <= $count; $i++) {
echo "id$i = ${'id'.$i}<br>";
echo "AB$i = ${'AB'.$i}<br>";
$result = mysql_query('UPDATE players SET G=G+1, AB=AB+${"AB".$i}, R=R+${"R".$i}, 1B=1B+${"1B".$i}, 2B=2B+${"2B".$i}, 3B=3B+${"3B".$i}, HR=HR+${"HR".$i}, RBI=RBI+${"RBI".$i}, SF=SF+${"SF".$i}, BB=BB+$${"BB".$i}, K=K+${"K".$i}, E=E+${"E".$i} WHERE id=${"id".$i}');
}

echo "Game results entered.";

} else {

echo "<div id='sectionheader'>Softball Update</div><br><br>";
$result = mysql_query("SELECT id, name FROM players WHERE team='Barons' AND year=2006 ORDER BY name");
$count = mysql_num_rows($result);
echo '<form method="post" action="">';
if ($myrow = mysql_fetch_array($result)) {
$i = 1;
echo "<table><tr><td colspan='13' align='center'>Barons</td></tr><tr><td>ID</td><td>Name</td><td>AB</td><td>R</td><td>1B</td><td>2B</td><td>3B</td><td>HR</td><td>RBI</td><td>SF</td><td>BB</td><td>K</td><td>E</td></tr>";
do {
$id = $myrow["id"];
$name = $myrow["name"];
echo "<tr><td><select name='id$i'><option value='$id'>$id</option></select></td>";
echo "<td><select name='name$i'><option value='$name'>$name</option></select></td>";
echo "<td><input type='text' name='AB$i' align='top' maxlength='2' size='2 '></td>";
echo "<td><input type='text' name='R$i' align='top' maxlength='2' size='2'></td>";
echo "<td><input type='text' name='1B$i' align='top' maxlength='2' size='2'></td>";
echo "<td><input type='text' name='2B$i' align='top' maxlength='2' size='2'></td>";
echo "<td><input type='text' name='3B$i' align='top' maxlength='2' size='2'></td>";
echo "<td><input type='text' name='HR$i' align='top' maxlength='2' size='2'></td>";
echo "<td><input type='text' name='RBI$i' align='top' maxlength='2' size='2'></td>";
echo "<td><input type='text' name='SF$i' align='top' maxlength='2' size='2'></td>";
echo "<td><input type='text' name='BB$i' align='top' maxlength='2' size='2'></td>";
echo "<td><input type='text' name='K$i' align='top' maxlength='2' size='2' ></td>";
echo "<td><input type='text' name='E$i' align='top' maxlength='2' size='2'></td></tr>";
$i = $i++;
} while ($myrow = mysql_fetch_array($result));
echo "</table>";
}

echo '<input type="hidden" name="count" value="$count">';
echo '<input type="submit" name="submit" value="Submit"><br><br>';
echo '</form>';

}
?>

</div></td></tr></table>
</body>
</html>[/quote]

Your help is greatly appreciated!
Link to comment
Share on other sites

Thanks. This is what I've got now:

[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]if ($_POST['submit']) {

// update players' stats

$count = $_POST['count'];

for ($i = 1; $i <= $count; $i++) {
[b]${"id".$i} = $_POST[id$i];[/b]
${"AB".$i} = $_POST[AB$i];
${"R".$i} = $_POST[R$i];
${"1B".$i} = $_POST[1B$i];
${"2B".$i} = $_POST[2B$i];
${"3B".$i} = $_POST[3B$i];
${"HR".$i} = $_POST[HR$i];
${"RBI".$i} = $_POST[RBI$i];
${"SF".$i} = $_POST[SF$i];
${"BB".$i} = $_POST[BB$i];
${"K".$i} = $_POST[K$i];
${"E".$i} = $_POST[E$i];

$result = mysql_query('UPDATE players SET G=G+1, AB=AB+${"AB".$i}, R=R+${"R".$i}, 1B=1B+${"1B".$i}, 2B=2B+${"2B".$i}, 3B=3B+${"3B".$i}, HR=HR+${"HR".$i}, RBI=RBI+${"RBI".$i}, SF=SF+${"SF".$i}, BB=BB+$${"BB".$i}, K=K+${"K".$i}, E=E+${"E".$i} WHERE id=${"id".$i}');
}[/quote]

And I'm getting [!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]Parse error: syntax error, unexpected T_VARIABLE, expecting ']'[/quote] for the line in bold above...?

Link to comment
Share on other sites

Thanks...no errors now. However, still not posting to the db. I suspect my $count hidden variable from the form is not being passed through or something of that sort b/c when I echo it after submitting, it comes back empty.

What is wrong with the way the $count variable is being passed?
Link to comment
Share on other sites

[code] echo '<input type="hidden" name="count" value="$count">';[/code]

Single quote does not parse variables. You need to use double quotes or concatenation
[code]
echo "<input type=\"hidden\" name=\"count\" value=\"$count\">";
// OR //
echo '<input type="hidden" name="count" value="'.$count.'">';

[/code]
Link to comment
Share on other sites

Instead of generating names like that, use arrays for the names. It will make your life so much simplier.

[code]<?php
$cols = array('AB','R','B1','B2','B3','HR','RBI','SF','BB','K','E');
if (isset($_POST['submit'])) {

// update players' stats

  $count = $_POST['count'];

  for ($i = 1; $i <= $count; $i++) {
    echo 'id[' . $i . '] = ' . $_POST['id'][$i] . "<br>";
    echo 'AB[' . $i . '] = ' . $_POST['AB'][$i] . "<br>";
    $qtmp = array();
    foreach ($_POST as $k => $dmy)
       switch($k) {
            case 'G':
                $qtmp[] = 'G = G + 1';
                break;
            case 'id':
            case 'submit':
//
//   do nothing
//
                 break;
            default: // all other fields
                 $qtmp[] = $k . '=' . $k . '+' . $_POST[$k][$i];
                 break;
    }
    $q = "UPDATE players SET " . implode(', ',$qtmp) . " where id=" . $_POST['id'][$i];
    $result = mysql_query($q) or die("Problem updating DB, query: $q<br>" . mysql_error());
  }

  echo "Game results entered.";

} else {

   echo "<div id='sectionheader'>Softball Update</div><br><br>";
   $result = mysql_query("SELECT id, name FROM players WHERE team='Barons' AND year=2006 ORDER BY name");
   $count = mysql_num_rows($result);
   echo '<form method="post" action="">';
   if ($count > 0) {
      $i = 1;
      echo "<table><tr><td colspan='13' align='center'>Barons</td></tr>
               <tr>
               <td>ID</td>
               <td>Name</td>
               <td>AB</td>
               <td>R</td>
               <td>1B</td>
               <td>2B</td>
               <td>3B</td>
               <td>HR</td>
               <td>RBI</td>
               <td>SF</td>
               <td>BB</td>
               <td>K</td>
               <td>E</td>
               </tr>";

       while ($myrow = mysql_fetch_assoc($result)) {
           $id = $myrow["id"];
           $name = $myrow["name"];
           echo '<tr><td><input type="hidden" name="id[' . $i .]' value="' . $id .'">$id</td>';
           echo '<td><input name="name[' . $i . ']" value="' . $name . '">$name</td>';
           foreach ($cols as $col)
               echo '<td><input type='text' name="' . $col . '[' . $i .']" align="top" maxlength="2" size="2"></td>';
           echo "</tr>";
           $i++;
       }
       echo "</table>";
    }

    echo '<input type="hidden" name="count" value="' . $count . '">';
    echo '<input type="submit" name="submit" value="Submit"><br><br>';
    echo '</form>';

}
?>[/code]

You will notice that I made extensive changes to your code... [img src=\"style_emoticons/[#EMO_DIR#]/smile.gif\" style=\"vertical-align:middle\" emoid=\":smile:\" border=\"0\" alt=\"smile.gif\" /]
Just a few comments on the changes:[list][*]You can't have names in PHP that start with numbers so I changed your '1B', '2B', and '3B' to 'B1', 'B2', and 'B3'[*]Using a <select> tag with one <option> didn't make any sense, I changed those to hidden fields[*]I used a foreach loop to generate the repeating input lines[*]I generate the update query via a switch statement within a foreach loop[*]This code hasn't been tested for correctness or syntax errors. [img src=\"style_emoticons/[#EMO_DIR#]/smile.gif\" style=\"vertical-align:middle\" emoid=\":smile:\" border=\"0\" alt=\"smile.gif\" /] YMMV[/list]
Ken
Link to comment
Share on other sites

thanks, kenrbnsn. you've gotten me 95% of the way there. right now, the generated mysql query is also trying to update NAME and COUNT. If I can exclude those variables from the update query and add the "G = G+1" line into the query, then I'm golden. Unfortunately, your technically svelte query is now out of my league so I don't know how to do it myself. Please advise.

Thanks much!
Link to comment
Share on other sites

I got NAME out of the update query...now trying to figure out how to get the COUNT out of the update query, and how to get the "G=G+1" into it.

Here's what I have so far:

[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]<?php

$cols = array('AB','R','B1','B2','B3','HR','RBI','SF','BB','K','E');
if (isset($_POST['submit'])) {

// update players' stats

$count = $_POST["count"];
$id = $_POST["id"];

for ($i = 1; $i <= $count; $i++) {
echo 'id[' . $i . '] = ' . $_POST['id'][$i] . "<br>";
echo 'AB[' . $i . '] = ' . $_POST['AB'][$i] . "<br>";
echo 'R[' . $i . '] = ' . $_POST['R'][$i] . "<br>";
echo 'B1[' . $i . '] = ' . $_POST['B1'][$i] . "<br>";
echo 'B2[' . $i . '] = ' . $_POST['B2'][$i] . "<br>";
echo 'B3[' . $i . '] = ' . $_POST['B3'][$i] . "<br>";
echo 'HR[' . $i . '] = ' . $_POST['HR'][$i] . "<br>";
echo 'RBI[' . $i . '] = ' . $_POST['RBI'][$i] . "<br>";
echo 'SF[' . $i . '] = ' . $_POST['SF'][$i] . "<br>";
echo 'BB[' . $i . '] = ' . $_POST['BB'][$i] . "<br>";
echo 'K[' . $i . '] = ' . $_POST['K'][$i] . "<br>";
echo 'E[' . $i . '] = ' . $_POST['E'][$i] . "<br>";

$qtmp = array();
foreach ($_POST as $k => $dmy)
switch($k) {
case 'G':
$qtmp[] = 'G = G + 1';
break;
case 'id':
case 'submit':
//
// do nothing
//
break;
default: // all other fields
$qtmp[] = $k . '=' . $k . '+' . $_POST[$k][$i];
break;
}
$q = "UPDATE players SET " . implode(', ',$qtmp) . " where id=" . $_POST['id'][$i];
$result = mysql_query($q) or die("Problem updating DB, query: $q<br>" . mysql_error());
}

echo "Game results entered.";

} else {

echo "<div id='sectionheader'>Softball Update</div><br><br>";
$result = mysql_query("SELECT id, name FROM players WHERE team='Barons' AND year=2006 ORDER BY name");
$count = mysql_num_rows($result);
echo '<form method="post" action="">';
if ($count > 0) {
$i = 1;
echo "<table><tr><td colspan='13' align='center'>Barons</td></tr>
<tr>
<td>ID</td>
<td>Name</td>
<td>AB</td>
<td>R</td>
<td>1B</td>
<td>2B</td>
<td>3B</td>
<td>HR</td>
<td>RBI</td>
<td>SF</td>
<td>BB</td>
<td>K</td>
<td>E</td>
</tr>";

while ($myrow = mysql_fetch_assoc($result)) {
$id = $myrow["id"];
$name = $myrow["name"];
echo '<input type="hidden" name="id[' . $i . ']" value="' . $id . '">';
echo "<tr><td>$id</td>";
echo "<td>$name</td>";
foreach ($cols as $col)
echo '<td><input type="text" name="' . $col . '[' . $i .']" align="top" maxlength="2" size="2"></td>';
echo "</tr>";
$i++;
}
echo "</table>";
}


echo '<input type="hidden" name="count" value="' . $count . '">';
echo '<input type="submit" name="submit" value="Submit"><br><br>';
echo '</form>';

}
?>[/quote]
Link to comment
Share on other sites

Before I did that, I was getting this error:

[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]id[1] = 2
AB[1] = 3
R[1] = 3
B1[1] = 3
B2[1] = 0
B3[1] = 0
HR[1] = 0
RBI[1] = 3
SF[1] = 0
BB[1] = 0
K[1] = 0
E[1] = 3
Problem updating DB, query: UPDATE players SET G=G+1, AB=AB+3, R=R+3, B1=B1+3, B2=B2+0, B3=B3+0, HR=HR+0, RBI=RBI+3, SF=SF+0, BB=BB+0, K=K+0, E=E+3, count=count+ where id=2
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where id=2' at line 1[/quote]

When I added the lines you suggested, I got this error:

[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]id[1] = 2
AB[1] = 6
R[1] = 6
B1[1] = 6
B2[1] = 0
B3[1] = 0
HR[1] = 0
RBI[1] = 6
SF[1] = 0
BB[1] = 0
K[1] = 0
E[1] = 6
id[2] = 1
AB[2] =
R[2] =
B1[2] =
B2[2] =
B3[2] =
HR[2] =
RBI[2] =
SF[2] =
BB[2] =
K[2] =
E[2] =
Problem updating DB, query: UPDATE players SET G=G+1, AB=AB+, R=R+, B1=B1+, B2=B2+, B3=B3+, HR=HR+, RBI=RBI+, SF=SF+, BB=BB+, K=K+, E=E+ where id=1
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' R=R+, B1=B1+, B2=B2+, B3=B3+, HR=HR+, RBI=RBI+, SF=SF+, BB=BB+, K=K+, E=E+ wher' at line 1[/quote]

I seem to be losing all the variable data in the update query now. As a wild guess, I tried adding a BREAK; after each line but that didn't work.

The code now looks like this:
[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]$qtmp = array();
foreach ($_POST as $k => $dmy)
switch($k) {
// case 'G':
// $qtmp[] = 'G = G + 1';
// break;
case 'id':
case 'submit':
case 'count':

//
// do nothing
//
break;
default: // all other fields
$qtmp[] = $k . '=' . $k . '+' . $_POST[$k][$i];
break;
}
$q = "UPDATE players SET G=G+1, " . implode(', ',$qtmp) . " where id=" . $_POST['id'][$i];[/quote]

How do I fix this?
Link to comment
Share on other sites

Change:
[code]<?php
default: // all other fields
$qtmp[] = $k . '=' . $k . '+' . $_POST[$k][$i];
?>[/code]
to
[code]<?php
default: // all other fields
if ($_POST[$k][$i] != '') $qtmp[] = $k . '=' . $k . '+' . $_POST[$k][$i];
?>[/code]
and
[code]<?php
$q = "UPDATE players SET G=G+1, " . implode(', ',$qtmp) . " where id=" . $_POST['id'][$i];
?>[/code]
to
[code]<?php
if (!empty($qtmp)) {
      $q = "UPDATE players SET G=G+1, " . implode(', ',$qtmp) . " where id=" . $_POST['id'][$i];
       $result = mysql_query($q) or die("Problem updating DB, query: $q<br>" . mysql_error());
}
?>[/code]

Ken
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.