Jump to content

Repeat a drop down list on each row of a HTML table


Go to solution Solved by Danishhafeez,

Recommended Posts

Hi all

I want to display the same drop down list (selection) in every row of my table but I can't seem to work out how to do it, the drop down always seems to come at the end of the table and not on each row.
The drop down list is a SQL query (a stored procedure) which is called.

I managed to get the dropdown to appear in the correct place when it's just one row in a table.

 


<?php

    $statement = db()->prepare("EXEC fe_uspAdminUserShowRegisteredAgencies");
    $statement->execute();
    $agencies= $statement->fetchAll(PDO::FETCH_ASSOC);
    ?>

<p>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
  <body>

  <table>
    <thead>
 <tr bgcolor="#FFF8DC"></b>
    <th><center><i>inviter</th>
    <th><center><i>inviter email</th>
    <th><center><i>inviter contact</th>
    <th><center><i>inviter region</th>
    <th><center><i>inviter skill</th>
        <th>refer to</th>
        <th></th>
</i>
</center>
   </tr>
</thead>
<p>
</p>
<?php 
if($inviterdetails) {
        foreach ($inviterdetails as $inviterdetail)
    {
    echo "<tr bgcolor=#FFF8DC>";
    echo "<td><center>" . $inviterdetail['fullname'] . "</td>";
    echo "<td><center>" . $inviterdetail['inviteremail'] . "</td>";
    echo "<td><center>" . $inviterdetail['invitercontact'] . "</td>";
    echo "<td><center>" . $inviterdetail['inviterregion'] . "</td>";
    echo "<td><center>" . $inviterdetail['inviterskill'] . "</td>";
    echo "<form action=LogReferal.php?email=referto>";
    // echo "<td><left><input type=email id=referto name=referto></td>";
    echo "<input type=hidden name=referred value=$inviterdetail[inviteremail]>";
    echo "<td><left><input type=submit value=refer></td>";
    }
}
 
?>  
<td><select name="referto" id ="referto"> 
<?php
foreach($agencies as $agencylist)
{
    echo "<option><name=referto type=email>" . $agencylist['email'] . "</option>";
}

Produces the desired result

image.thumb.png.f50ab03ec6a5a77585afe49a47843453.png

However when I try to repeat the process in a separate table which has multiple rows, I get the selection drop down all over the place in this case at the end of the row

and not applicable to any particular row. I have managed to get it everywhere except on the row it should be and it doesn't repeat and be relevant to the row.

 

 

 

image.thumb.png.bc7130be60e1f0466736b763a9355d5a.png


<?php
//Connection details section..

$email = current_user(); 
    $statement = db()->prepare("EXEC fe_uspConnectionDetails ?;");
    $statement->bindParam(1, $email, PDO::PARAM_STR); 
    $statement->execute();
    $details = $statement->fetchAll(PDO::FETCH_ASSOC);
    ?>
<p>

<p>
<table>
    <thead>
 <tr>
    <th><i>name</th>
    <th><i>email</th>
    <th><i>skill</th>
    <th><i>mobile</th>
    <th><i>region</th>
    <th><i>days</th>
    <th><i><center>refer to</center></th>
</tr>
</thead>
         <hr color="#c7c34c" size="4" width="50%">
         <p><i>my connections (below)</i></p>
<?php

if($details) {
        foreach ($details as $detail)
    {
 
    echo "<td><left>" . $detail['fullname'] . "</td>";
    echo "<td><left>" . $detail['connectionemail'] . "</td>";
    echo "<td><left>" . $detail['skill'] . "</td>";
    echo "<td><left>" . $detail['phonenumber'] . "</td>";
    echo "<td><left>" . $detail['region'] . "</td>";
    echo "<td><left>" . $detail['daysremaining'] . "</td>";
    echo "<form action=LogReferal.php?email=referto>";
    // echo "<td><left><input type=email id=referto name=referto></td>";
    echo "<input type=hidden name=referred value=$detail[connectionemail]>";
    echo "<td><left><input type=submit value=refer></td>";
    
    // echo "<form action=LogReferal.php?email=referto>";
    // // echo "<td><left><input type=email id=referto name=referto></td>";
    // echo "<input type=hidden name=referred value=$inviterdetail[inviteremail]>";
    // echo "<td><left><input type=submit value=refer></td></tr></form>";

    }
 
}


?>  
<td><select name="referto" id ="referto"> 
<?php
foreach($agencies as $agencylist)
{
    echo "<option><name=referto type=email>" . $agencylist['email'] . "</option>";
}


?>
</td>

I kind of realise the repeating code (for each) has to be somewhere in the main table and not outside the table but I have just got stuck...

Any help greatly received

Cheers

 

Greg

 

Link to comment
Share on other sites

you can put a complete html table inside a single form and you can put a complete form inside a single table cell (th or td), but you cannot spread forms out, inside of multiple cells, in a single html table. also, all the html you are outputting inside the html table, that is not inside of a table cell is being rendered above the table. i recommend that you validate the resulting html markup at validator.w3.org

either all the markup in your first example didn't get posted or it is broken and only seems to produce the correct result because there's a single form and a single table row (tr.)

your second example, in addition to what @dodgeitorelse3 has posted, has no opening or closing  <tr> </tr> tags, and the select tag and form tag will need to be closed in each pass through the details loop.

 

Link to comment
Share on other sites

I prefer to use a function to build the options from an array (or query results), creating the html for the options and selecting the appropriate item.

An example is below.

DATA USED

RESOURCE                                   USER
+----+--------------------+                +----+----------+--------------+     
| id | description        |                | id | username | fullname     |     
+----+--------------------+                +----+----------+--------------+     
| 1  |  Car - C43 GBT     |                | 1  | tess     | Tess Tickell |     
| 2  | Van - D76 GBT      |                | 2  | hugh     | Hugh Jass    |     
| 3  | Minibus - MN11 BUS |                | 3  | tom      | Tom DiCanari |     
+----+--------------------+                | 4  | lucy     | Lucy Lastik  |     
  |                                        +----+----------+--------------+     
  |                                           | 
  +---------+                                 |
            |                                 +---------------------+
            |                                                       |
BOOKING     |                                                       |
+----+-------------+---------------------+---------------------+---------+
| id | resource_id | book_start          | book_end            | user_id |
+----+-------------+---------------------+---------------------+---------+
| 1  | 1           | 2024-05-13 09:00:00 | 2024-05-13 12:00:00 | 1       |
| 2  | 1           | 2024-05-13 12:00:00 | 2024-05-13 17:00:00 | 2       |
| 4  | 1           | 2024-05-16 12:00:00 | 2024-05-16 18:00:00 | 3       |
| 5  | 2           | 2024-05-13 11:30:00 | 2024-05-17 18:00:00 | 4       |
+----+-------------+---------------------+---------------------+---------+

OUTPUT EXAMPLE

image.png.e02d1fe1154e19784c7783bb73cf9b7f.png

CODE EXAMPLE

<?php
require 'db_inc.php';                // USE YOUR OWN ...
$pdo = mdbConnect('db1');            // ... CONNECTION CODE

################################################################################
## Build arrays of dropdown options   
################################################################################
    $res = $pdo->query("SELECT id, description
                        FROM resource
                        ORDER BY description
                       ");
    $results = $res->fetchAll();
    $resources = array_column($results, 'description', 'id');
    
    
    $res = $pdo->query("SELECT id, fullname
                        FROM user
                        ORDER BY fullname
                       ");
    $results = $res->fetchAll();
    $users = array_column($results, 'fullname', 'id');
    
    /***************************************************************************
    * function to generate menu options from array and select current value
    * 
    * @param array $optArray  Array of menu options
    * @param mixed $current   Currnt value to be selected
    */
        function menuOptions(&$optArray, $current='')
        {
            $opts = "<option value=''>- select -</option>\n";
            foreach ($optArray as $val => $txt)   {
                $sel = $val==$current ? 'selected' : '';
                $opts .= "<option $sel value='$val'>$txt</option>\n";
            }
            return $opts;
        }
    
################################################################################
## Build html table for sreen display   
################################################################################
    $res = $pdo->query("SELECT b.id as bid
                             , r.id as rid
                             , u.id as uid
                             , date_format(b.book_start, '%b %d - %h:%i%p') as stime
                             , date_format(b.book_end, '%b %d - %h:%i%p') as etime
                        FROM booking b
                             JOIN user u ON b.user_id = u.id
                             JOIN resource r ON b.resource_id = r.id
                        ORDER BY rid, book_start, book_end
                       ");
    $tdata = '';
    foreach ($res as $r)  {
        $tdata .= "<tr>
                       <td>{$r['bid']}</td>
                       <td><select name='resid'>" . menuOptions($resources, $r['rid']) . "</select></td>
                       <td><select name='userid'>" . menuOptions($users, $r['uid']) . "</select></td>
                       <td>{$r['stime']}</td>
                       <td>{$r['etime']}</td>
                    </tr>   
                  ";
    }
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="utf-8">
<title>Example</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style type='text/css'>
    table {
        border-collapse: collapse;
        width: 100%;
    }
    th, td {
        padding: 8px;
    }
    th {
        border: 1px solid white;
        background-color: black;
        color: white;
    }
</style> 
</head>
<body>

<header class='w3-indigo w3-padding'>
    <h1>Dropdown Menus</h1>
</header>

<table border='1'>
    <tr><th>ID</th>
        <th>Item</th>
        <th>User</th>
        <th>From</th>
        <th>Until</th>
    </tr>
    <?=$tdata?>
</table>
<br>
<?=pdo2text($pdo, "select * from resource")?>
</body>
</html>

 

Link to comment
Share on other sites

  • Solution

To ensure the dropdown appears in the correct position within each row, you need to place the <select> element inside the loop that iterates over your $details array. The issue arises because the <select> element is currently being added outside the loop, which causes it to appear only once at the end of the table. Additionally, the form tags should also be inside the loop to ensure each row has its own form, dropdown, and submit button.

 

<?php
// Connection details section..
$email = current_user();
$statement = db()->prepare("EXEC fe_uspConnectionDetails ?;");
$statement->bindParam(1, $email, PDO::PARAM_STR);
$statement->execute();
$details = $statement->fetchAll(PDO::FETCH_ASSOC);

// Fetch agencies for dropdown
$statement = db()->prepare("EXEC fe_uspAdminUserShowRegisteredAgencies");
$statement->execute();
$agencies = $statement->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>
<table>
    <thead>
        <tr>
            <th><i>name</i></th>
            <th><i>email</i></th>
            <th><i>skill</i></th>
            <th><i>mobile</i></th>
            <th><i>region</i></th>
            <th><i>days</i></th>
            <th><i><center>refer to</center></i></th>
        </tr>
    </thead>
    <tbody>
<?php
if ($details) {
    foreach ($details as $detail) {
        echo "<tr>";
        echo "<td><left>" . $detail['fullname'] . "</td>";
        echo "<td><left>" . $detail['connectionemail'] . "</td>";
        echo "<td><left>" . $detail['skill'] . "</td>";
        echo "<td><left>" . $detail['phonenumber'] . "</td>";
        echo "<td><left>" . $detail['region'] . "</td>";
        echo "<td><left>" . $detail['daysremaining'] . "</td>";
        echo "<td><left>";
        echo "<form action='LogReferal.php?email=referto' method='POST'>";
        echo "<input type='hidden' name='referred' value='" . $detail['connectionemail'] . "'>";
        echo "<select name='referto' id='referto'>";
        foreach ($agencies as $agencylist) {
            echo "<option value='" . $agencylist['email'] . "'>" . $agencylist['email'] . "</option>";
        }
        echo "</select>";
        echo "<input type='submit' value='refer'>";
        echo "</form>";
        echo "</td>";
        echo "</tr>";
    }
}
?>
    </tbody>
</table>
</body>
</html>

Data Fetching: First, fetch both the connection details and the agency list.

HTML Structure: The HTML structure now includes the <select> dropdown within each row of the table.

Loop and Form: The loop iterates over each $detail and adds a row in the table. The form, including the hidden input for the referred value and the dropdown for referto, is inside this loop. This ensures each row has its own form and dropdown, associated correctly with the row's data.

Form Method: Ensure the form uses the POST method to securely send data.

 

Best Regard

Danish Hafeez | QA Assistant

ICTInnovations

Link to comment
Share on other sites

Wow @Barand what an amazing script  you have given me. I will certainly be using the code again.

However I finally went with @dodgeitorelse3 solution of adding the foreach into the table (below).  I knew it needed to be in there somewhere just couldn't figure it out.

Thanks to all who replied it now works a treat. It's messy but it works I will look to refine it the way @Barand suggests as that seems way more controllable and repeatable.

Thanks all

Greg

 


if($details) {
        foreach ($details as $detail)
    {
 
    echo "<td><left>" . $detail['fullname'] . "</td>";
    echo "<td><left>" . $detail['connectionemail'] . "</td>";
    echo "<td><left>" . $detail['skill'] . "</td>";
    echo "<td><left>" . $detail['phonenumber'] . "</td>";
    echo "<td><left>" . $detail['region'] . "</td>";
    echo "<td><left>" . $detail['daysremaining'] . "</td>";
    echo "<form action=LogReferal.php?email=referto>";
    echo "<td><select name=referto id= referto>" ;
        foreach($agencies as $agencylist)
    {
    echo "<option><name=referto type=email>" . $agencylist['email'] . "</option>";
    }
    echo "<input type=hidden name=referred value=$detail[connectionemail]>";
    echo "<td><left><input type=submit value=refer></td></tr>";
    }

}

image.thumb.png.944223c593601b30a488d1ab50e62fd1.png

Link to comment
Share on other sites

1 hour ago, Danishhafeez said:

To ensure the dropdown appears in the correct position within each row, you need to place the <select> element inside the loop that iterates over your $details array. The issue arises because the <select> element is currently being added outside the loop, which causes it to appear only once at the end of the table. Additionally, the form tags should also be inside the loop to ensure each row has its own form, dropdown, and submit button.

 

<?php
// Connection details section..
$email = current_user();
$statement = db()->prepare("EXEC fe_uspConnectionDetails ?;");
$statement->bindParam(1, $email, PDO::PARAM_STR);
$statement->execute();
$details = $statement->fetchAll(PDO::FETCH_ASSOC);

// Fetch agencies for dropdown
$statement = db()->prepare("EXEC fe_uspAdminUserShowRegisteredAgencies");
$statement->execute();
$agencies = $statement->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>
<table>
    <thead>
        <tr>
            <th><i>name</i></th>
            <th><i>email</i></th>
            <th><i>skill</i></th>
            <th><i>mobile</i></th>
            <th><i>region</i></th>
            <th><i>days</i></th>
            <th><i><center>refer to</center></i></th>
        </tr>
    </thead>
    <tbody>
<?php
if ($details) {
    foreach ($details as $detail) {
        echo "<tr>";
        echo "<td><left>" . $detail['fullname'] . "</td>";
        echo "<td><left>" . $detail['connectionemail'] . "</td>";
        echo "<td><left>" . $detail['skill'] . "</td>";
        echo "<td><left>" . $detail['phonenumber'] . "</td>";
        echo "<td><left>" . $detail['region'] . "</td>";
        echo "<td><left>" . $detail['daysremaining'] . "</td>";
        echo "<td><left>";
        echo "<form action='LogReferal.php?email=referto' method='POST'>";
        echo "<input type='hidden' name='referred' value='" . $detail['connectionemail'] . "'>";
        echo "<select name='referto' id='referto'>";
        foreach ($agencies as $agencylist) {
            echo "<option value='" . $agencylist['email'] . "'>" . $agencylist['email'] . "</option>";
        }
        echo "</select>";
        echo "<input type='submit' value='refer'>";
        echo "</form>";
        echo "</td>";
        echo "</tr>";
    }
}
?>
    </tbody>
</table>
</body>
</html>

Data Fetching: First, fetch both the connection details and the agency list.

HTML Structure: The HTML structure now includes the <select> dropdown within each row of the table.

Loop and Form: The loop iterates over each $detail and adds a row in the table. The form, including the hidden input for the referred value and the dropdown for referto, is inside this loop. This ensures each row has its own form and dropdown, associated correctly with the row's data.

Form Method: Ensure the form uses the POST method to securely send data.

 

Best Regard

Danish Hafeez | QA Assistant

ICTInnovations

Hi Danish
@Danishhafeez
Anyway I can get the refer button on the same line? I have followed your code now

image.thumb.png.db94aac70eeadc54d24227ade1360c14.png
 

Link to comment
Share on other sites

1 hour ago, mac_gyver said:

and if you validate the resulting web page, you will find all the broken and obsolete markup -

 

Yes I have been using that since your suggestion, it's truly amazing! Small things and all that! 

Link to comment
Share on other sites

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.