Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder MaDmiX's Avatar
    Join Date
    Feb 2012
    Location
    Charlotte, NC
    Posts
    160
    Thanks
    40
    Thanked 0 Times in 0 Posts

    Using a variable as column selector

    Hi All,

    I have the following code to select a column in my query based on the user's selection in a form:

    PHP Code:
    if(isset($_POST['Locations'])) {$Location $_POST['Locations'];}

    mysql_select_db($database_connEngSupport$connEngSupport);
    $query_rstTheLocation "SELECT 'tblDropMenusID', '".$Location."' FROM tbldropmenus";
    $rstTheLocation mysql_query($query_rstTheLocation$connEngSupport) or die(mysql_error());
    $row_rstTheLocation mysql_fetch_assoc($rstTheLocation); 
    Now I try to use the query results later in my script as follows:

    PHP Code:
      <?php do { ?>
        <form action="admin-update-goto.php" method="post" name="frmDeleteItem" >
          <table width="100%">
            <tr>
              <td><?php echo $row_rstTheLocation['".$Location."']; ?></td>
              <td><input name="deleteItem" type="submit" value="Delete" class="button" /></td>
              </tr>
            </table>
          <input type="hidden" name="delItemID" value="<?php echo $row_rstTheLocation['tblDropMenusID']; ?>" />
        </form>
      <?php } while ($row_rstTheLocation mysql_fetch_assoc($rstTheLocation)); ?>
    But I am getting a "Notice: Undefined index: ".$Location." in...", referring to this line:
    PHP Code:
    <td><?php echo $row_rstTheLocation['".$Location."']; ?></td>
    If I try the line like this:
    PHP Code:
    <td><?php echo $row_rstTheLocation[$Location]; ?></td>
    I don't get the error but I get the column name instead of the query results. Can someone show me what I am doing wrong here?

    TIA,

    Ken

  • #2
    Regular Coder MaDmiX's Avatar
    Join Date
    Feb 2012
    Location
    Charlotte, NC
    Posts
    160
    Thanks
    40
    Thanked 0 Times in 0 Posts
    UPDATE:

    Got it figured out! I modified my query a bit (thanks to PHPMyAdmin) and got the correct syntax. I also added a filter to filter out empty strings:

    PHP Code:
    if(isset($_POST['Locations'])) {$Location $_POST['Locations'];}

    mysql_select_db($database_connEngSupport$connEngSupport);
    $query_rstTheLocation "SELECT `tblDropMenusID`, `".$Location."` FROM `tbldropmenus` WHERE `".$Location."` NOT LIKE ''";
    $rstTheLocation mysql_query($query_rstTheLocation$connEngSupport) or die(mysql_error());
    $row_rstTheLocation mysql_fetch_assoc($rstTheLocation); 
    And:

    PHP Code:
    <td><?php echo $row_rstTheLocation[$Location]; ?></td>
    Thanks!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •