Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-05-2007, 08:24 PM   PM User | #1
steamngn
Regular Coder

 
Join Date: May 2004
Location: Hudson Valley, NY
Posts: 147
Thanks: 6
Thanked 0 Times in 0 Posts
steamngn is an unknown quantity at this point
Build Grid info for insert from text field?

I must need more rest....
How about this one: I have a MYSQL table (ITEM_GRIDS) that holds grid info for items such as size, colors, etc...
The table has 4 basic columns:
Code:
ITEM_NO,GRID_1,GRID_2,GRID_3
and data is stored like this:
Code:
item     grid_1     grid_2     grid_3
---------------------------------
123      small       black      short sleeve
123      small       black      long sleeve
123      small       white      short sleeve
123      small       white      long sleeve
123      medium    black      short sleeve
123      medium    black      long sleeve
etc...
Ok, for the PHP part:
I would like to create a page to insert/edit/delete grid info for an item. Since each grid_x column will have multiple entries for 1 item, how can I create a page to show all of them, edit say 1 of them, and then save the changes?
Since we won't know how many entries, we really can't do one text field per column per entry. I was thinking of having a text field for each grid column, having one entry per row (or some other delimitation) and then looping through them to build the grid for insert/update. any ideas???
__________________
(Management+Coworkers)<>Logic
steamngn is offline   Reply With Quote
Old 07-06-2007, 04:20 PM   PM User | #2
mylegoh
New Coder

 
Join Date: Jul 2006
Location: London
Posts: 36
Thanks: 0
Thanked 0 Times in 0 Posts
mylegoh is an unknown quantity at this point
Arrays

You will need to use a multi-dimensional array to display and retrieve info for storage.
mylegoh is offline   Reply With Quote
Old 07-06-2007, 04:22 PM   PM User | #3
steamngn
Regular Coder

 
Join Date: May 2004
Location: Hudson Valley, NY
Posts: 147
Thanks: 6
Thanked 0 Times in 0 Posts
steamngn is an unknown quantity at this point
good day mylegoh!
I realize the multi dimentional array idea, but how to read from the text box into the array? Is this even possible?
Andy
__________________
(Management+Coworkers)<>Logic
steamngn is offline   Reply With Quote
Old 07-06-2007, 04:29 PM   PM User | #4
mylegoh
New Coder

 
Join Date: Jul 2006
Location: London
Posts: 36
Thanks: 0
Thanked 0 Times in 0 Posts
mylegoh is an unknown quantity at this point
Using arrays

Yes.

What you do is create an array like:
$grid[0]['item']
$grid[0]['grid 1']
$grid[0]['grid 2']

Now access your database and store the data in the array.

Next read the array to build your form (note each field will have a name such as 'item$x' where $x is the iterative value from say, a for loop which you would be using to access the array.

Now your function which will be in the form action field will then read all the fields putting them into an array, you are now going in the opposite direction so you want $POST_[$field] where $field will be something like $field = 'item'. $c where $c is again the iterative value.

Then process your array as normal.

Good luck,
mylegoh is offline   Reply With Quote
Old 07-06-2007, 04:32 PM   PM User | #5
steamngn
Regular Coder

 
Join Date: May 2004
Location: Hudson Valley, NY
Posts: 147
Thanks: 6
Thanked 0 Times in 0 Posts
steamngn is an unknown quantity at this point
ok,
So I will reference the same text box over and over in the loop; how do I delineate each row/value? \n for enter?
hate to ask so many questions, just can't seem to get my head around this...
Andy
__________________
(Management+Coworkers)<>Logic
steamngn is offline   Reply With Quote
Old 07-06-2007, 04:43 PM   PM User | #6
mylegoh
New Coder

 
Join Date: Jul 2006
Location: London
Posts: 36
Thanks: 0
Thanked 0 Times in 0 Posts
mylegoh is an unknown quantity at this point
Example

Hi,
I have included a function below, which does exactly what you need and i hope will be a good example for you to use.
Summary, this function displays in a table format all the products in a database so the user can amend, add or delete.
The table contains extra blank fields which are used for insertion.
Ignore the SESSION bits, that is used to mimic javascript behaviour where it is turned off in a browser.

PHP Code:
        function products()
        {
            echo 
"<div>\n";

            
// connect to db

            
$db preparedb(ACCOUNTSDB);
            if (!
$db)
            {
                
$error_msg ="Database error on connection. ".
                            
"Function - products() in page.inc  - SqNo:0010";
                
error_manager(E_USER_ERROR,$error_msg);
                die(
DIEMESSAGE);
            }

            
// INITIAL DATA VALUES ARE SET

            // redisplay of form after error, where javascript disabled will show
            //    user's typed data.

            
$products = array();

            if ( 
$_SESSION['cms_name4form'] == 'products' )
            {
                
$products     $_SESSION['cms_array'];
                
$itemcount    $_SESSION['cms_itemcount'];
            }
            else
            {
                
//    --    retrieve and store any aliases for this account

                
$tbl TBLPROD;
                
$where "";
                
$order "name";

                  
$result selectrow ($db,$tbl,"*",$where,$order);

                  if (!
$result || get_rowcnt($result) === false
                {
                    
$error_msg ="Failure on selectrow of $tbl. ".
                                
"Function - products() in page.inc  - SqNo:0030";
                    
error_manager(E_USER_ERROR,$error_msg);
                    die(
DIEMESSAGE);
                }

                for ( 
$p 0$p get_rowcnt($result); $p++ )
                {            
                    
$row getrow($result);

                    
$products[$p]['rec_idx']= $row['product_idx'];
                    
$products[$p]['type']    = cleantxt_4print($row['product_type']);
                    
$products[$p]['domain']    = cleantxt_4print($row['domain_type']);
                    
$products[$p]['sitemap']= cleantxt_4print($row['sitemap']);
                    
$products[$p]['name']    = cleantxt_4print($row['name']);
                    
$products[$p]['price']     = $row['price'];
                    
$products[$p]['desc']     = cleantxt_4print($row['description']);
                    
$products[$p]['delete']    =    "";
                }

                
// --    add blank line for extra input

                
for ( $m $p$m $p+10$m++ )
                {
                    
$products[$m]['rec_idx']= 0;
                    
$products[$m]['type']    = "template";
                    
$products[$m]['name']    = INPDEFAULT;
                    
$products[$m]['domain']    = 'na';
                    
$products[$m]['sitemap']= 'na';
                    
$products[$m]['price']     = "0.00";
                    
$products[$m]['desc']     = INPDEFAULT;
                    
$products[$m]['delete']    =    INPDEFAULT;
                }

                
$itemcount  $m;
            }

            
//    --    User details form

            
$cnt 0;

            echo 
"<h1>CMS - Product Management</h1>";
            echo 
"<h2>Add, amend or delete.</h2>";

            echo 
"<form name='navigation' method='post' action='"CODELIB"cms_products.php'>\n";

            echo 
"<p><input type='hidden' name='name4form' value='products' readonly='readonly'/></p>\n";    
            echo 
"<p><input type='hidden' name='return_url' value='index.php?pg=$this->page' readonly='readonly'/></p>\n";    

            echo 
"<table summary='This is a table of all the current products.'>";
            echo 
"<tr>\n";
            echo 
"<th scope='col'></th>".
                    
"<th scope='col'>Type</th>".
                    
"<th scope='col'>Name</th>".
                    
"<th scope='col'>Price</th>".
                    
"<th scope='col'>Description</th>".
                    
"<th scope='col'>Delete</th>";
            echo 
"</tr>\n";                

            
//    -- output the details

            
for ( $k 0$k $itemcount$k++ )
            {            
                    echo 
"<tr>";
            
                    echo 
"<th scope='row'>". ++$cnt"</th>\n";
                    echo 
"<td><input type='hidden' name='rec_idx$cnt' value='"$products[$k]['rec_idx'].
                                
"' readonly='readonly'/>\n".
                        
"<select name='type$cnt' tabindex='". ++$this->tab"' >".
                        
"<option value='template'"is_selected('template'$products[$k]['type']).
                        
">Template</option>".
                        
"<option value='website'"is_selected('website'$products[$k]['type']).
                        
">Website</option></select>";

                    echo 
"<br/>Use following only when type is <b>Website</b>.";
                    echo 
"<br/>Domain: <select name='domain$cnt' tabindex='". ++$this->tab"' >".
                        
"<option value='na'"is_selected('na'$products[$k]['domain']).
                        
">Not applicable</option>".
                        
"<option value='domain'"is_selected('domain'$products[$k]['domain']).
                        
">Domain</option>".
                        
"<option value='sub'"is_selected('sub'$products[$k]['domain']).
                        
">Sub-domain</option></select> ";

                    echo 
" Site: <select name='sitemap$cnt' tabindex='". ++$this->tab"' >".
                        
"<option value='na'"is_selected('na'$products[$k]['sitemap']).
                        
">Not applicable</option>".
                        
"<option value='two'"is_selected('two'$products[$k]['sitemap']).
                        
">2-page</option>".
                        
"<option value='multi'"is_selected('multi'$products[$k]['sitemap']).
                        
">Multi-page</option>".
                        
"<option value='full'"is_selected('full'$products[$k]['sitemap']).
                        
">Full site</option>";
                    echo 
"</select>";                    

                    echo 
"</td>\n";

                    echo 
"<td>\n".
                            
"<input type='text' name='name$cnt' size='30' maxlength='150' ".
                            
"value='"$products[$k]['name']. "' tabindex='". ++$this->tab"'/></td>\n";

                    echo 
"<td>\n".
                            
"<input type='text' name='price$cnt' size='10' maxlength='10' ".
                            
"value='"$products[$k]['price']. "' tabindex='". ++$this->tab"'/></td>\n";

                    echo 
"<td>\n".
                            
"<textarea name='desc$cnt' rows='1' cols='40' tabindex='". ++$this->tab"'>".
                            
$products[$k]['desc']. "</textarea></td>\n";

                    echo 
"<td>";
                    if ( 
$products[$k]['rec_idx'] > && !is_null($products[$k]['rec_idx']) )
                    {
                        echo 
"<input type='checkbox' name='delete$cnt' value='delete'".
                                
is_selected($products[$k]['delete'], 'delete''c').  " tabindex='". ++$this->tab"'/>";
                    }
                    echo 
"</td>\n";
                    echo 
"</tr>";                
                    if ( 
$k%== )
                    {
                        echo 
"<tr><td colspan='6'>";
                        
$this -> add_go2top();
                        echo 
"<div class='formbtnright'>".
                                
"<a href='"CODELIB"cms_cancel.php?pg=index.php?pg=$this->page' title='Cancel'><img src='"IMAGELIB.
                                    
"cancel.gif' alt='Cancel' width='64' height='24'/></a>&nbsp;&nbsp;".
                                
"<input class='btn' type='reset' value='Reset' title='Reset or clear this form' tabindex='".
                                    ++
$this->tab"'/>&nbsp;&nbsp;".
                                        
"<input class='btn' type='submit' value='Save changes' title='Save changes'".
                                            
" tabindex='".
                                            ++
$this->tab"'/></div>\n";
                        echo 
"</td></tr>\n";

                        echo 
"<tr>\n";
                        echo 
"<th scope='col'></th>".
                                
"<th scope='col'>Type</th>".
                                
"<th scope='col'>Name</th>".
                                
"<th scope='col'>Price</th>".
                                
"<th scope='col'>Description</th>".
                                
"<th scope='col'>Delete</th>";
                        echo 
"</tr>\n";                
                    }
            }

            echo 
"</table>";
            echo 
"<p><input type='hidden' name='itemcount' value='$itemcount' readonly='readonly'/></p>\n";

            echo 
"<div class='formbtnleft'>".
                    
"<a href='"CODELIB"cms_cancel.php?pg=index.php?pg=$this->page' title='Cancel'><img src='"IMAGELIB.
                        
"cancel.gif' alt='Cancel' width='64' height='24'/></a>&nbsp;&nbsp;".
                    
"<input class='btn' type='reset' value='Reset' title='Reset or clear this form' tabindex='".
                        ++
$this->tab"'/>&nbsp;&nbsp;".
                            
"<input class='btn' type='submit' value='Save changes' title='Save changes'".
                                
" tabindex='".
                                ++
$this->tab"'/></div>\n";

            echo 
"</form>\n";

            
$this -> add_go2top();

            echo 
"</div>\n";
        } 
This is the cms_products.php - form action bit
PHP Code:
<?php
// -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//
//    Function     :  cms_products.php
//    Version         : 1.00
// Last Update    :
//    Latest CCNo    :
//    ----------------------------
//
//    Copyright (c) Y2Pods Solutions. All rights reserved.
//
// -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

//    --    PRODUCTS MANAGEMENT
//    --
//    -- This function will add, amend or delete
//    --

    
session_start();
    require_once (
'cms_always.inc');
    
    
//    --    Anti - hack measures
    // First, make sure the form was posted from a browser.
    // For basic web-forms, we don't care about anything
    // other than requests from a browser:
   
    
if (!isset($_SERVER['HTTP_USER_AGENT']) )
    {
        
$error_msg "Hack Warning! Form content not from a browser. ".
            
"Function - cms_products.php - SqNo:0010";
        
error_manager(E_USER_ERROR,$error_msg);
        die(
DIEMESSAGE);
    }

    
// Make sure the form was indeed POST'ed:
    //  (requires your html form to use: action="post")

    
if (!$_SERVER['REQUEST_METHOD'] == "POST")
    {
        
$error_msg "Hack Warning! Form method not POST. ".
            
"Function - cms_products.php - SqNo:0020";
        
error_manager(E_USER_ERROR,$error_msg);
        die(
DIEMESSAGE);
    }

    
//    -- retrieve and validate all data from form

    //    --    store details in session for on error return
    //    -- used to redisplay content if javascript disabled

    
$_SESSION['name4form']        = 'products';
    
$_SESSION['cms_itemcount']    = $_POST['itemcount'];
    
$_SESSION['cms_return_url']= $_POST['return_url'];
    
$return_url                        $_POST['return_url'];

    
$products = array();

    for (
$i 0$i $_POST['itemcount']+1$i++ )
    {
        
$idx_txt        'rec_idx'. ($i+1);
        
$type_txt    'type'. ($i+1);
        
$name_txt    'name'. ($i+1);
        
$sitemap_txt'sitemap'. ($i+1);
        
$domain_txt    'domain'. ($i+1);
        
$price_txt    'price'. ($i+1);
        
$desc_txt    'desc'. ($i+1);
        
$del_txt        'delete'. ($i+1);

        
$products[$i]['rec_idx']= $_POST[$idx_txt];
        
$products[$i]['name']    = trim($_POST[$name_txt]);
        
$products[$i]['type']    = trim($_POST[$type_txt]);
        
$products[$i]['sitemap']= trim($_POST[$sitemap_txt]);
        
$products[$i]['domain']    = trim($_POST[$domain_txt]);
        
$products[$i]['price']    = $_POST[$price_txt];
        
$products[$i]['desc']    = trim($_POST[$desc_txt]);
        
$products[$i]['delete'] = $_POST[$del_txt];
    }

    
$_SESSION['cms_array'] = $products;

    
$sub_array = array();
    
$cnt 0;

    for (
$i 0$i $_POST['itemcount']+1$i++ )
    {
        if ( !(
$products[$i]['name'] == INPDEFAULT || strlen($products[$i]['name']) == )  
                 || 
$products[$i]['rec_idx'] != )
        {        
            
//    Validation of content
            
if (!isvalid_inputfield($products[$i]['desc'],'text',255) )
            {
                
$err_msg "<p>The description input ".
                                
"at line $i is too long (max. 255) or contains unprintable characters.</p>";
                exit(
ERRORBEGIN$err_msgGOBACK);        
            }
// add validation to ensure that domain and sitemap is added for type website ??????????

            
$products[$i]['name']         = clean4input($products[$i]['name']);
            
$products[$i]['desc']         = clean4input($products[$i]['desc']);

            
$sub_array[$cnt++] = array('id'            => $products[$i]['rec_idx'],
                                            
'type'        =>    $products[$i]['type'],
                                            
'name'        =>    $products[$i]['name'],
                                            
'sitemap'    =>    $products[$i]['sitemap'],
                                            
'domain'        =>    $products[$i]['domain'],
                                            
'price'        =>    $products[$i]['price'],
                                            
'description'=> $products[$i]['desc'],
                                            
'delete'        =>    $products[$i]['delete']);
        }
    }

    
//    -- decide processing based on whether creation or amendment

    
$db=preparedb(ACCOUNTSDB);
    if (!
$db)
    {
        
$error_msg ="Database error on connection. ".
                    
"Function - cms_products.php  - SqNo:0030";
                                
"MySQL error number - "mysql_errno(). " ".
                                
mysql_error(). "\r\n".
        
error_manager(E_USER_ERROR,$error_msg);
        die(
DIEMESSAGE);
    }

    
//    -- store the product and services details

    
$tbl TBLPROD;

    foreach (
$sub_array as $element)
    {
        
// decide if the record should be deleted, inserted or amended

        //    --    Delete
        
if ( $element['delete'] == 'delete')
        {            
            
$where "product_idx = "$element['id'];

            
$response deleterow($db$tbl$where);
            if (!
$response)
            {
                
$error_msg "Database Error - during $tbl deletion where $where. ".
                                
"MySQL error number - "mysql_errno(). " ".
                                
mysql_error(). "\r\n".
                            
"Function - cms_products.php - SqNo:0040";
                
error_manager(E_USER_ERROR,$error_msg);
                die(
DIEMESSAGE);
            }

            continue;
        }

        
//    --    Update            
        
if ( $element['id'] != )
        {            
            
$fieldval "name                = '"$element['name']. "', ".
                            
"product_type    = '"$element['type']. "', ".
                            
"price            = "$element['price']. ", ".
                            
"sitemap            = '"$element['sitemap']. "', ".
                            
"domain_type    = '"$element['domain']. "', ".
                            
"description    = '"$element['description']. "', ".
                            
"last_updated    =  NULL";

            
$where "product_idx = "$element['id']; 

            
$response updaterow($db$tbl$fieldval$where);
            if (!
$response)
            {
                
$error_msg "Database Error - during $tbl update where $where for values $fieldval.\r\n".
                                
"MySQL error number - "mysql_errno(). " ".
                                
mysql_error(). "\r\n".
                            
"Function - cms_products.php - SqNo:0050";
                
error_manager(E_USER_ERROR,$error_msg);
                die(
DIEMESSAGE);
            }

            continue;
        }

        
//    --    Insert
        
if ( $element['id'] == )
        {                    
            
$fieldval "name                    = '"$element['name']. "', ".
                            
"product_type        = '"$element['type']. "', ".
                            
"sitemap            = '"$element['sitemap']. "', ".
                            
"domain_type    = '"$element['domain']. "', ".
                            
"price                = "$element['price']. ", ".
                            
"description        = '"$element['description']. "', ".
                            
"access_level     = 100,".
                            
"last_updated        =  NULL,".
                            
"creation_date        =    NULL";  

            
$response insertrow ($db,$tbl,$fieldval);        //    created the record                                                                                            
            
if ($response === false)
            {
                
$error_msg "Database Error - during $tbl creation for values $fieldval.\r\n".
                                
"MySQL error number - "mysql_errno(). " ".
                                
mysql_error(). "\r\n".
                            
"Function - cms_products.php - SqNo:0060";
                
error_manager(E_USER_ERROR,$error_msg);
                die(
DIEMESSAGE);
            }

            continue;
        }
    }            
//    --    end foreach statement

    //    -- optimize table

    
$query "optimize table $tbl"
      
$result runquery ($db,$query);
      if (!
$result || get_rowcnt($result) === false 
    {
        
$error_msg ="Unable to runquery $query. \r\n".
                    
"MySQL error number - "mysql_errno(). " "mysql_error(). "\r\n".
                    
"Function - cms_products.php - SqNo:0080\r\n";
        
error_manager(E_USER_ERROR,$error_msg);
        die(
DIEMESSAGE);
    }
    
// --    unset the stored variables

    
unset($_SESSION['cms_name4form']);
    unset(
$_SESSION['cms_array']);
    unset(
$_SESSION['cms_return_url']);
    unset(
$_SESSION['cms_itemcount']);

    
// --    send the details to the next screen

    
$callstr CMSCODELIB"$return_url&res=true";

    
header("Location: $callstr");
?>
Hope this is useful.

mylegoh is offline   Reply With Quote
Old 07-06-2007, 04:51 PM   PM User | #7
steamngn
Regular Coder

 
Join Date: May 2004
Location: Hudson Valley, NY
Posts: 147
Thanks: 6
Thanked 0 Times in 0 Posts
steamngn is an unknown quantity at this point
Ahhhhhh....
Like manna from the gods!
I completely had no thoughts at ALL about table-set, and this just got the lightbulbs glowing! I will work with this for a bit and report back my progress.
Much thanks!
Andy
__________________
(Management+Coworkers)<>Logic
steamngn is offline   Reply With Quote
Old 07-06-2007, 04:54 PM   PM User | #8
mylegoh
New Coder

 
Join Date: Jul 2006
Location: London
Posts: 36
Thanks: 0
Thanked 0 Times in 0 Posts
mylegoh is an unknown quantity at this point
Thumbs up

You are welcome!
Happy to help ... and do let me know how it goes.
mylegoh is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:41 AM.


Advertisement
Log in to turn off these ads.