1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Submitting multiple values to the same MySQL field

Discussion in 'Programming' started by Nathan Franklin, Dec 12, 2014.

  1. #1
    Not sure if that's worded correctly but basically I have a form that submits Size, Colour & Style from an admin page to our MySQL database. Currently it only submits 1 of the options even if more than one are ticked.

    I've attached the form any help is greatly appreciated!

    You can view the form -
    <?php
    //Written by Alexander James Reed.
    //This script is an admin creation panel script. Used for creating or uploading items into a database driven site. This is the only script involved in the creation process.
    include ("../aReedApi/aReedApi.php");
    include ("../globals.php");
    
    //Open database
    aReed_MySQLOpenConnectionDatabase($global_databaseName, $global_databaseUser, $global_databasePassword);
    
    //Declare variables
    //Get category Id
    $currentProductCategoryId = $_POST['productCategoryId'];
    
    //Get sub category Id
    $currentProductSubCategoryId = $_POST['productSubCategoryId'];
    
    //Define error handling variables
    $allValid = true;
    $error_noName = false;
    
    //Define success
    $successfullyAdded = false;
    $successMessage = "Product has been successfully created.";
    
    //Define input value variables
    $inputValue_name = "";
    $inputValue_image = "";
    $inputValue_priceRRP = "";
    $inputValue_price = "";
    $inputValue_colour = "";
    $inputValue_width = "";
    $inputValue_pileWeight = "";
    $inputValue_construction = "";
    $inputValue_hotOffer = "";
    $inputValue_seoDescription = "";
    $inputValue_seoTitle = "";
    $inputValue_seoKeywords = "";
    
    
    //Define this scripts main submit button name and submit action
    $mainSubmitName = "createProduct";
    $mainSubmitCaption = "Create Product";
    $mainSubmitAction = $currentPage =  $_SERVER["REQUEST_URI"];
    
    //Define the creation panel's caption. This is also the titles page
    $creationPanelCaption = "Create a new product";
    
    //Define database
    $database_table = "product_" . $currentProductCategoryId . "_" . $currentProductSubCategoryId;
    $database_insertQuery = "";
    
    //See if this script has been submitted
    if (isset($_POST[$mainSubmitName]))
    {
        //Get input values
        $inputValue_name = $_POST['name'];
        $inputValue_image = $_FILES['image']['name'];   
        $inputValue_priceRRP = $_POST['priceRRP'];
        $inputValue_price = $_POST['price'];
        $inputValue_colour = $_POST['colour'];
        $inputValue_width = $_POST['width'];
        $inputValue_pileWeight = $_POST['pileWeight'];
        $inputValue_construction = $_POST['construction'];
        $inputValue_hotOffer = $_POST['hotOffer'];
        $inputValue_seoDescription = $_POST['seoDescription'];
        $inputValue_seoTitle = $_POST['seoTitle'];
        $inputValue_seoKeywords = $_POST['seoKeywords']; 
       
        if ($inputValue_name == "")
        {
            $error_noName = true;
            $allValid = false;
        }   
    
        //See if any errors have occoured
        if ($allValid == true)
        {       
            //Generate permalink from name
            $generatedPermalink = aReed_generatePermalink($inputValue_name);
    
            //Get current maximum order id
            if (aReed_MySQLContainsData(aReed_MySQLGetTableData($database_table)) == true)
            {
                $newOrderId = mysql_query("SELECT MAX(orderId) as orderId FROM `" . $database_table . "`");
                $newOrderId = mysql_result($newOrderId, 0, "orderId");
                $newOrderId = $newOrderId + 1;
            }
            else
                $newOrderId = 0;
           
            //Loop through all filters
            $filterItems = aReed_MySQLGetTableData("filter", "orderId", "ASC");
            $filterString = "";
            while($currentFilter = mysql_fetch_array($filterItems))
            {                       
                //Loop through all filter tags on this filter
                $filterTagItems = aReed_MySQLGetTableData("filterTag_" . $currentFilter['filterId'], "orderId", "ASC");
                while($currentFilterTag = mysql_fetch_array($filterTagItems))
                {
                    //Add tag to filter string
                    $filterString .= $currentFilter['filterId'] . "_" . $_POST['filterTag_' . $currentFilter['filterId']] . "|";
                }
            } 
           
            //Define database data query
            $database_insertQuery = "''," .
                    "'" . $inputValue_name . "', " .
                    "'" . $inputValue_image . "', " .               
                    "'" . $inputValue_priceRRP . "', " .
                    "'" . $inputValue_price . "', " .
                    "'" . $inputValue_colour . "', " .
                    "'" . $inputValue_width . "', " .
                    "'" . $inputValue_pileWeight . "', " .
                    "'" . $inputValue_construction . "', " .
                    "'" . $inputValue_hotOffer . "', " .
                    "'" . $generatedPermalink . "', " .
                    "'" . $newOrderId . "', " .
                    "'" . $inputValue_seoDescription . "', " .
                    "'" . $inputValue_seoTitle . "', " .
                    "'" . $inputValue_seoKeywords . "', " .
                    "'" . $filterString . "'";
           
            //Write the new item to the database
            aReed_MySQLInsertNewRowIntoTable($database_table, $database_insertQuery);       
                   
            //Get new item id
            $newItemId = aReed_MySQLFindTableRow($database_table, "name", $inputValue_name);
            $newItemId = aReed_MySQLExtractFieldValueFromResult($newItemId, "productId");
           
            //Write as hot offer if needed       
            if ($inputValue_hotOffer == "yes")
            {
                $database_insertQuery = "''," .
                        "'" . $inputValue_name . "', " .
                        "'" . $inputValue_image . "', " .               
                        "'" . $inputValue_priceRRP . "', " .
                        "'" . $inputValue_price . "', " .
                        "'" . $inputValue_colour . "', " .
                        "'" . $inputValue_width . "', " .
                        "'" . $inputValue_pileWeight . "', " .
                        "'" . $inputValue_construction . "', " .
                        "'" . $inputValue_hotOffer . "', " .
                        "'" . $generatedPermalink . "', " .
                        "'" . $newOrderId . "', " .
                        "'" . $inputValue_seoDescription . "', " .
                        "'" . $inputValue_seoTitle . "', " .
                        "'" . $inputValue_seoKeywords . "', " .
                        "'" . $filterString . "', " .
                        "'" . $currentProductCategoryId . "_" . $newItemId . "'";
    
                //Write the new item to the database
                aReed_MySQLInsertNewRowIntoTable("hotOffers", $database_insertQuery); 
            }
           
            //Main image
            if ($inputValue_image != "")
            {
                //Create directory structure - Under time constraint. For some reason only sometimes these directorys are not created on product creation.
                $newPath = getcwd() . "/../images/products/category_" . $currentProductCategoryId . "/subCategory_" . $currentProductSubCategoryId . "/product_" . $newItemId . "/";
                if (!file_exists($newPath))
                    mkdir($newPath, 0777);
                $newPath = getcwd() . "/../images/products/category_" . $currentProductCategoryId . "/subCategory_" . $currentProductSubCategoryId . "/product_" . $newItemId . "/thumbnails/";
                if (!file_exists($newPath))
                    mkdir($newPath, 0777);  
               
                //Move the file to the correct location on the server
                move_uploaded_file($_FILES["image"]["tmp_name"], "../images/products/category_" . $currentProductCategoryId . "/subCategory_" . $currentProductSubCategoryId . "/product_" . $newItemId . "/" . $inputValue_image);
                /*move_uploaded_file($_FILES["image"]["tmp_name"], "../images/products/category_" . $currentProductCategoryId . "/subCategory_" . $currentProductSubCategoryId . "/product_" . $newItemId . "/thumbnails/" . $inputValue_image);*/
    
                if ($global_productThumbnailEnabled == true)
                {
                    //Resize the image if needed
                    $thumbnailImage = new imageModifier();
                    $thumbnailImage->loadImage("../images/products/category_" . $currentProductCategoryId . "/subCategory_" . $currentProductSubCategoryId . "/product_" . $newItemId . "/" . $inputValue_image);
                    $newSize = $thumbnailImage->getProportionateSize($global_productThumbnailWidth, $global_productThumbnailHeight);
                    $thumbnailImage->setSize($newSize['width'], $newSize['height']);
                    $thumbnailImage->saveImage("../images/products/category_" . $currentProductCategoryId . "/subCategory_" . $currentProductSubCategoryId . "/product_" . $newItemId . "/thumbnails/" . $inputValue_image);
                }
               
                if ($global_productImageResize == true)
                {
                    //Resize the image if needed
                    $resizedImage = new imageModifier();
                    $resizedImage->loadImage("../images/products/category_" . $currentProductCategoryId . "/subCategory_" . $currentProductSubCategoryId . "/product_" . $newItemId ."/" . $inputValue_image);
                    $newSize = $resizedImage->getProportionateSize($global_productImageWidth, $global_productImageHeight);
                    $resizedImage->setSize($newSize['width'], $newSize['height']);
                    $resizedImage->saveImage("../images/products/category_" . $currentProductCategoryId . "/subCategory_" . $currentProductSubCategoryId . "/product_" . $newItemId ."/" . $inputValue_image);
                }           
            }              
    
            //Reset input value
            $inputValue_name = "";
            $inputValue_priceRRP = "";
            $inputValue_price = "";
            $inputValue_colour = "";
            $inputValue_width = "";
            $inputValue_pileWeight = "";
            $inputValue_construction = "";
            $inputValue_hotOffer = "";
            $inputValue_seoDescription = "";
            $inputValue_seoTitle = "";
            $inputValue_seoKeywords = "";
    
            //Define success
            $successfullyAdded = true;
        }
    }
    ?>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <link href="style.css" rel="stylesheet" type="text/css"/>       
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>
                <?php $creationPanelCaption ?>
            </title>
        </head>
        <script type="text/javascript" src="../scripts/tiny_mce/tiny_mce.js"></script>
        <script type="text/javascript">
        tinyMCE.init({
                // General options
                mode : "exact",
                elements : "extendedDescription",
                theme : "advanced",
                plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
    
                // Theme options
                theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
                theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
                theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
                theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
                theme_advanced_toolbar_location : "top",
                theme_advanced_toolbar_align : "left",
                theme_advanced_statusbar_location : "bottom",
                theme_advanced_resizing : true,
    
                // Skin options
                skin : "o2k7",
                skin_variant : "silver",
    
                // Example content CSS (should be your site CSS)
                content_css : "css/example.css",
    
                // Drop lists for link/image/media/template dialogs
                template_external_list_url : "js/template_list.js",
                external_link_list_url : "js/link_list.js",
                external_image_list_url : "js/image_list.js",
                media_external_list_url : "js/media_list.js",
    
                // Replace values for the template plugin
                template_replace_values : {
                        username : "Some User",
                        staffid : "991234"
                }
        });
        </script>   
        <body style="text-align:center;">
            <div style="text-align: center;">
                <table style="width: 100%;">
                    <form enctype="multipart/form-data" action="<?php echo $mainSubmitAction; ?>" method="post">                   
                        <tr>
                            <th colspan="2" style="text-align: center;" class="rowOne">
                                <?php echo $creationPanelCaption; ?>
                            </th>
                        </tr>
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                Product title:
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">                           
                                <?php
                                aReed_createTextBox("name", $inputValue_name, "width: 99%;");
                                ?>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                Image:
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">
                                <?php
                                aReed_createFileButton("image");
                                ?>
                            </td>
                        </tr>       
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                Price per m2 RRP:
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">                           
                                <?php
                                aReed_createTextBox("priceRRP", $inputValue_priceRRP, "width: 99%;");
                                ?>
                            </td>
                        </tr>                      
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                Price per m2:
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">                           
                                <?php
                                aReed_createTextBox("price", $inputValue_price, "width: 99%;");
                                ?>
                            </td>
                        </tr>                   
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                Colour:
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">
                                <?php
                                aReed_createTextBox("colour", $inputValue_colour, "width: 99%;");
                                ?>
                            </td>
                        </tr>      
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                Width (m):
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">
                                <?php
                                aReed_createTextBox("width", $inputValue_width, "width: 99%;");
                                ?>
                            </td>
                        </tr>                             
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                Pile weight:
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">
                                <?php
                                aReed_createTextBox("pileWeight", $inputValue_pileWeight, "width: 99%;");
                                ?>
                            </td>
                        </tr>     
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                Construction:
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">
                                <?php
                                aReed_createTextBox("construction", $inputValue_construction, "width: 99%;");
                                ?>
                            </td>
                        </tr>          
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                Hot Offer?:
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">
                                <input type="checkbox" name="hotOffer" id="hotOffer" <?php if ($inputValue_hotOffer == "yes") echo "checked"; ?> value="yes"/>
                            </td>
                        </tr>                    
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                SEO Description:
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">
                                <?php
                                aReed_createTextBox("seoDescription", $inputValue_seoDescription, "width: 99%;");
                                ?>
                            </td>
                        </tr> 
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                SEO Title:
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">
                                <?php
                                aReed_createTextBox("seoTitle", $inputValue_seoTitle, "width: 99%;");
                                ?>
                            </td>
                        </tr> 
                        <tr>
                            <td style="width: 50%; text-align: right;" class="rowTwo">
                                SEO Keywords:
                            </td>
                            <td style="width: 50%; text-align: left;" class="rowTwo">
                                <?php
                                aReed_createTextBox("seoKeywords", $inputValue_seoKeywords, "width: 99%;");
                                ?>
                            </td>
                        </tr>
                        <tr>
                            <th colspan="2" style="text-align: center;" class="rowOne">
                                Search Tags
                            </th>
                        </tr>
                        <?php
                        //Loop through all filters
                        $filterItems = aReed_MySQLGetTableData("filter", "orderId", "ASC");
                        while($currentFilter = mysql_fetch_array($filterItems))
                        {                       
                            ?>
                            <tr>
                                <th colspan="2" style="text-align: center;" class="rowTwo">
                                    <u><?php echo $currentFilter['name']; ?></u>
                                    <br/>
                                    <?php
                                    //Loop through all filter tags on this filter
                                    $filterTagItems = aReed_MySQLGetTableData("filterTag_" . $currentFilter['filterId'], "orderId", "ASC");
                                    $filterTagId = 0;
                                    while($currentFilterTag = mysql_fetch_array($filterTagItems))
                                    {                                   
                                        ?>
                                        <input <?php if ($filterTagId == 0) echo "checked"; ?> type="checkbox" name="filterTag_<?php echo $currentFilter['filterId']; ?>" value="<?php echo $currentFilterTag['filterTagId']; ?>"/><?php echo $currentFilterTag['name']; ?>                                       
                                        <?php                                   
                                        $filterTagId++;                                   
                                    }
                                    ?>
                                </th>
                            </tr>                          
                            <?php
                        }
                        ?>                     
                        <tr>
                            <td colspan="2" style="text-align: center;" class="rowOne">
                                <input type="submit" name="<?php echo $mainSubmitName; ?>" value="<?php echo $mainSubmitCaption; ?>" class="inputButton"/>
                                <input type="hidden" name="productCategoryId" value="<?php echo $currentProductCategoryId; ?>"/>
                                <input type="hidden" name="productSubCategoryId" value="<?php echo $currentProductSubCategoryId; ?>"/>
                            </td>
                        </tr>
                    </form>
                    <form method="POST" action="admin_editproductcategory.php">
                        <tr>
                            <td colspan="2" style="text-align: center;" class="rowOne">
                                <input type="submit" name="backToAdmin" value="Back" class="inputButton"/>
                                <input type="hidden" name="productCategoryId" value="<?php echo $currentProductCategoryId; ?>"/>
                            </td>
                        </tr>  
                    </form>
                    <tr>
                        <td colspan="2" style="text-align: center;" class="rowOne">
                            <?php
                            //Display success
                            if ($successfullyAdded == true)
                            {
                                echo $successMessage;
                            }
    
                            //Display errors
                            if ($error_noName == true)
                            {
                                echo "* You must specifiy a product title.";
                            }
                            ?>
                        </td>
                    </tr>
                </table>
            </div>
        </body>
    </html>
    
    PHP:

     
    Nathan Franklin, Dec 12, 2014 IP
  2. Anveto

    Anveto Well-Known Member

    Messages:
    697
    Likes Received:
    40
    Best Answers:
    19
    Trophy Points:
    195
    #2
    I am not even finding an insert query, like the actual SQL.

    Anyways you could either make each value a row by having multiple insert statements or perhaps you could just use a json encoded array with json_encode() which can then be turned into an array again with json_decode()
     
    Anveto, Dec 12, 2014 IP
  3. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    Wow.... that's some really horrible code. Truly horrible. What's the point of having all these functions and such? I have a vague hope that the constructs provide some sort of data-validation on the backend, but looking at this I really doubt it.
    As @MarkusTenghamn , there isn't a distinct insert-query in the code you posted, so there is no way to know what is being sent to the database. Try echoing out the full query (most likely this needs t be done somewhere in the aReedAPI.php-file, but my suggestion would be to rewrite this properly - using something else than mysql_ (outdated, deprecated and insecure), proper syntax (table to align a form? Really?).
     
    PoPSiCLe, Dec 12, 2014 IP
    Anveto likes this.
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #4
    The bloated presentational markup being vomited up by it is no winner either.

    As @PoPSiCLe implied but really didn't put the emphasis on, you really need the riot act read to you about still using the mysql_ functions that we've been told for over EIGHT YEARS to stop using, and for three years have had giant red warning boxes in the manual waving you off from since they will most likely be disappearing very soon. They are insecure, inefficient, and generally speaking a miserable steaming pile of /FAIL/ at web development... kind of like your bloated gibberish non-semantic markup.(Semantic is a polite way of saying "Using HTML properly")

    As to what's being asked, that's why we have prepared queries in MODERN SQL implementations. For example if $db was a connected PDO object:

    $statement = $db->prepare('
      INSERT INTO whatever (
         fieldName
      ) values (
        ?
      )
    ');
    foreach ($valueArray as $value) $db->execute([$value]);
    Code (markup):
    Prepare once, execute multiple times. For smaller data sets some people might recommend using explode and collapse to build the query so a single execute can be passed, but if the data set gets larger those functions can take longer than just calling execute multiple times... HOW large really hinges on the data AND the server it's run on, so I would just loop the values.

    It's one of the entire reasons to use prepared queries -- alongside things like zero risk of SQL infection (if you turn prepare emulation off) since you are sending the data SEPARATE from the query string. Much like in HTML how what things look like has ZERO business in the markup, on modern SQL Queries the data has no damned business in the query!
     
    deathshadow, Dec 12, 2014 IP
  5. Nathan Franklin

    Nathan Franklin Member

    Messages:
    43
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    45
    #5
    Thanks for the feedback guys, I know close to nothing about code and the majority of my skills involve replacing links.

    We've used the same coder for years and he doesn't have time to fix this so I thought i'd see if you had anything to say.

    Maybe it's time we upgrade if he is really as bad as you're all saying!
     
    Nathan Franklin, Dec 13, 2014 IP
  6. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #6
    If he doesn't have time to fix this, it might be time to find someone who's got the time, and who's also up to date on modern coding principles. Your coder might not be the worst out there, but he's VERY outdated.
     
    PoPSiCLe, Dec 13, 2014 IP
    deathshadow likes this.
  7. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #7
    ... and outdated most likely means insecure a well.

    Though I'd say said developer isn't just outdated, I'd say he also has no clue how to write HTML, how to write PHP, what CSS is or how to use it... or a dozen other things a developer should know before being allowed to develop anything for anyone else. See all the endless pointless "variables for nothing".
     
    deathshadow, Dec 13, 2014 IP