Jump to content
Sign in to follow this  
ohad

Question about arrays and html table

Recommended Posts

Hi

 

I have a table i populate from database (upon a parameter the user insert and with PHP $_GET i take this value and populate the table accordint to if). After I allow the user to add or edit data in rows by using jquery. The last part I do is to want to save the changes back to database using PHP.

The jquery i use suppose to serve different tables. So its written in a way that get the table structure and add rows upon it. In this example I put it in the index page

Everything works fine,but I cant build the array from the added rows. My variables in the php part got null values (although in debug mode I see that $_POST... store data in the array

What do I miss here?

Thanks

here is my php+ html part of index,php

<?php
    require_once("../xxx/Includes/GlDbOra.php");
    
    if(isset($_POST['submit_btn']))
    {
        $catalog_id=$_GET['catalog_id'];
        $tableRow = $_POST['tableRow'];
        foreach ($tableRow as $row)
        {
            $item_id=$row['ITEM_ID'];
            $item_name=$row['ITEM_NAME'];
            $userid=$_SESSION['userid'];
            $program='PHP';
            $stid=DBOracle::getInstance()->insert_items($catalog_id, $item_id, $item_name, $userid, $program);
        }
    }
    if (!empty($_GET['catalog_id']))
    {
        $catalog_id=trim($_GET['catalog_id']);
        $catalog_id_desc=$_GET['catalog_id_desc'];
        $stid=DBOracle::getInstance()->get_items($catalog_id);
    }   
?>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Items</title>
        <script type="text/javascript" src="../../Bundles/php-ajax/jquery-3.5.1.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
        <script type="text/javascript" src="../../Bundles/bootstrap-4.5.0-dist/js/bootstrap.min.js"></script>
        <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
        <link href="../../Bundles/bootstrap-4.5.0-dist/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> 
        <link href="../xxx/css/global_style.css" type="text/css" rel="stylesheet" madia="all"/> 
    </head>
    <body>
        <div id="page-wrap">
            <section id="main-content">
                <div id="guts">
                    <span style="clear: both; float: left; margin-left: 5%;">
                       <form id="param_form" name="populate_table" method="GET" action="index.php">
                            <label for="catalog_id">Catalog Id</label>
                            <input type="text" name="catalog_id" class="catalog_id" id="left_radius_textbox" value=" <?php echo htmlspecialchars($catalog_id, ENT_QUOTES); ?>" placeholder="<?php echo catalog_id; ?>"/>
                            <input type="text" name="catalog_id_desc" class="catalog_id_desc" id="right_radius_textbox" value=" <?php echo htmlspecialchars($catalog_id_desc, ENT_QUOTES); ?>" readonly />
                            <button class="load_form"><span class="glyphicon glyphicon-refresh"></span> Get Data</button>
                        </form>
                    </span>
                    <br>
                    <div class="container">
                        <div class="row">
                            
                            <div class="panel  panel-primary filterable">
                                <div class="panel-heading">
                                    <h3 class="panel-title">Items</h3>
                                    <div class="pull-right">
                                        <button class="btn btn-default btn-xs btn-filter"><span class="glyphicon glyphicon-filter"></span> Filter</button>
                                    </div>
                                </div>
                                <form id="form" name="form1" method="POST" action="">
                                    <table class="table table-fixed"  id="tab_logic">
                                       <thead>
                                            <tr class="filters" id ="table_header_2_btn">
                                                <th class="col-xs-2"><input type="text"  name="tableRow[0]['ITEM_ID']" value="" placeholder="Item Id" disabled></th>
                                                <th class="col-xs-6"><input type="text"  name="tableRow[0]['ITEM_NAME']" value="" placeholder="Description" disabled></th>
                                                <th class="col-xs-4"></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $catalog_id=$_GET['catalog_id'];
                                            $count=0;
                                                while ($row= oci_fetch_array($stid, OCI_ASSOC)):
                                                    echo "<tr>";
                                                    echo "<td class=".'"col-xs-2"><input name="tableRow['.$count.']['."'ITEM_ID']".'"'.' value="'.htmlspecialchars($row['ITEM_ID'], ENT_QUOTES).'" style='."'border:none;".'></td>"';
                                                    echo "<td class=".'"col-xs-6"><input name="tableRow['.$count.']['."'ITEM_NAME']".'">'.htmlspecialchars($row['ITEM_NAME'], ENT_QUOTES)."</td>";
                                                    $count++;
                                            ?>
                                            <td class="col-xs-4">
                                                <a class="add" title="Add" data-toggle="tooltip"><i class="material-icons"></i></a>
                                                <a class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons"></i></a>
                                                <a class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons"></i></a>
                                            </td>
                                            <?php
                                                echo "</tr>\n";
                                                endwhile;
                                                oci_free_statement($stid);
                                                oci_close($con);
                                            ?>
                                        </tbody>
                                        <tr>
                                            <button class="regular_button" id="add-new"><span class="glyphicon glyphicon-plus"></span> Add Rows</button>
                                            <td><input type="submit" name="submit_btn" value="Submit"></td>
                                        </tr>
                                    </table>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
      <script>
     
      </script>
  </body>
</html>

and here is the jquery part in the index.php (that in between the <script></script>)

$(document.body).on('click', '#add-new', function() 
{
    $('[data-toggle="tooltip"]').tooltip();
    var actions = $("#tab_logic td:last-child").html();
    $(this).attr("disabled", "disabled");
    var index = $("#tab_logic tbody tr:last-child").index();
	var newRow = $("<tr>");
    var cols = "";
    var element_string='';
    var table_structure = $('#table_header_2_btn')[0].innerHTML;
    table_structure=$.trim(table_structure);
    var arrStr = table_structure.split(/\n/g);
    for(var i=0; i<arrStr.length-1; i++)
    {    
        arrStr[i] =$.trim(arrStr[i]);
        element_string=arrStr[i];
        if (element_string.indexOf('<th')!=-1)
        {
            var n=element_string.indexOf('<th');
            element_string='<td'+ element_string.substr(n+3);
            var n=element_string.indexOf('[0]');
            element_string= element_string.substr(0,n)+'['+index+']'+element_string.substr(n+3);
        }
        if (element_string.indexOf('placeholder=')!=-1)
        {
            var n=element_string.indexOf('placeholder=');
            element_string=element_string.substr(0,n-1);
            element_string=element_string  + '</td>';
        }
        cols+=element_string;
    }
    cols+='<td class="col-xs-4">' + actions + '</td>' 
    cols +='</tr>';
    newRow.append(cols);
    $('#tab_logic').append(newRow);
    $("#tab_logic tbody tr").eq(index + 1).find(".add, .edit").toggle();
    $('[data-toggle="tooltip"]').tooltip();
});


    $(document).on("click", ".add", function()
    {
        var empty = false;
        var input = $(this).parents("tr").find('input[type="text"]');
        input.each(function()
        {
            if(!$(this).val())
            {
                $(this).addClass("error");
                empty = true;
            }
            else
            {
                $(this).removeClass("error");
            }
        });
        $(this).parents("tr").find(".error").first().focus();
        if(!empty)
        {
            input.each(function()
            {
  //              $(this).parent("td").html($(this).val());
            });			
            $(this).parents("tr").find(".add, .edit").toggle();
            $("#add-new").removeAttr("disabled");
        }		
    });


    $(document).on("click", ".edit", function()
    {		
        $(this).parents("tr").find("td:not(:last-child)").each(function()
        {
            $(this).html('<input type="text" value="' + $(this).text() + '">');
        });		
        $(this).parents("tr").find(".add, .edit").toggle();
        $("#add-new").attr("disabled", "disabled");
    });


    $(document).on("click", ".delete", function()
    {
        $(this).parents("tr").remove();
        $("#add-new").removeAttr("disabled");
    });

 

Share this post


Link to post
Share on other sites

there are a number of issues in the code that are producing php errors. to get php to help you, find the php.ini that php is using and set error_reporting to E_ALL, display_errors to ON, and output_buffing to OFF. stop and start your web server to get any changes made to the php.ini to take effect.

you need to ALWAYS validate inputs to your code before using them. 

if you are selecting from existing catalog (id) values, you should have some type of select menu and not require the user to remember and type in values.

another recommendation is to separate the database specific code, that knows how to query for and fetch data, from the presentation code, that knows how to produce the output from that data. to do this, just fetch all the data into an appropriately named php variable, then test/loop over this variable in the html document. this will make testing easier, since you can 'see' if all the data you are getting is what you expect (it also makes asking for help easier since someone can make up some data to see what your code is actually doing, without needing any of your actual database information.)

next, add the following line of code near the start of your php code so that you can see what data is actually being submitted -

echo '<pre>'; print_r($_POST); echo '</pre>';

by putting the numerical index 1st, the array(s) of data being submitted are not what you think.

lastly, the reason you are not getting the ITEM_NAME form fields is because the html markup is broken. don't concatenate things unless needed. you should also validate your resulting html markup at validator.w3.org 

Edited by mac_gyver

Share this post


Link to post
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.

Sign in to follow this  

×
×
  • 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.