Page 1 of 2

Advice needed on getting large page to load quicker

Posted: Mon Sep 21, 2009 4:56 am
by barb woolums
I have a php page that takes a long time to load.

It is a form for entering a recipe so there are a lot of duplicated select fields ( 20 instances of unit of measure, ingredient, and 2 preparation methods - a total of 80 selects which could have really long option lists) with the same option lists which are populated from a postgresql db.

At the moment I loop through the records returned from the database to build the option list for each select.

Would it be quicker if I put the db results into an array to build the option lists?

The other option I had thought of was to reduce the number of selects displayed and add them only if required usiing innerhtml to dynamically add content.

I need advice on the approach that is going to give me the best improvement in load time.

Any ideas?

Re: Advice needed on getting large page to load quicker

Posted: Mon Sep 21, 2009 6:42 am
by robnet
80 queries seems a lot for one page, that's probably where your bottleneck is.

If you paste the code we can look at reducing these.

Re: Advice needed on getting large page to load quicker

Posted: Mon Sep 21, 2009 4:21 pm
by barb woolums
Thanks for the quick response!!

Here's the code. There are only about 12 queries on the page, it's just that they are referened many times for the duplicated fields.

Code: Select all

 
<?PHP
    require_once('top.php');
?>
<script type="text/javascript" language="javascript" src="javascripts/jquery-1.3.1.min.js"></script>
<script type="text/javascript" src="javascripts/jquery.livequery.js"></script>
<script type="text/javascript" src="javascripts/jquery.cookie.js"></script>
<script src="dhtmlxCombo/codebase/dhtmlxcommon.js"></script>
<script src="dhtmlxCombo/codebase/dhtmlxcombo.js"></script>
<script src="dhtmlxCombo/codebase/ext/dhtmlxcombo_whp.js"></script>
<script src="dhtmlxCombo/codebase/ext/dhtmlxcombo_extra.js"></script>
<script type="text/javascript" src="javascripts/decode.js"></script>
<script type="text/javascript" src="javascripts/my.add.recipe.js"></script>
<script type="text/javascript" src="javascripts/my.image.js"></script>
<script type="text/javascript" src="javascripts/my.menu.js"></script>
<script type="text/javascript" src="javascripts/ajaxupload.3.5.js"></script>
<link rel='STYLESHEET' type='text/css' href='dhtmlxCombo/codebase/dhtmlxcombo.css'>
<script type="text/javascript" language="javascript" src="javascripts/my.menu.js"></script>
<script type="text/javascript" language="javascript">
window.dhx_globalImgPath="dhtmlxCombo/codebase/imgs/";
</script>
</head>
<?php
    require_once('banner.php');
    
    $id = $_POST['id'];
    
    if($id>0) {
        $sql = "SELECT directions, note, added FROM recipe WHERE id=$id";
        $rsrecipe = pg_query($connection,$sql);
        $directions = pg_result($rsrecipe, 0, 0);
        $note = pg_result($rsrecipe, 0, 1);
        $added = pg_result($rsrecipe, 0, 2);
    }
?>
<tr><td>
    <div id="hidemenu"><a href="#">Hide Menu</a></div>
</td><td>
    <div id="showmenu" style="display: none"><a href="#">Show Menu</a></div>
<?php
    if ($user=='demo') {
        echo '<br><table cellpadding="0" cellspacing="0" border="0" width="82" align="left" style=" height:18px;" class="order">';
        echo '<tr><td align="center" valign="middle" width="78" style="padding:3px 0px 0px 0px; background:url(wrmimages/recipes-btn_2_1.gif) left top no-repeat; "><a href="index-3.html" style="color:white;text-decoration:none;">BUY NOW</a></td><td><img src="wrmimages/recipes-spacer.gif" width="4" height="1" alt="Web Based Recipe Management Online"></td></tr>';
        echo '</table>';
    } else {
        echo '<a style="float:right" href="display_edit.php?logout">Logout</a>';
    }
?>
</td></tr>
<tr><td height="100%" style = "border-right: thin dotted #9E9A7B;">
    <div id="sidebar"><?PHP require_once('addmenu.php')?></div>
    </td>
<td height="100%">
<h2 style="font-size:18px">Add Recipe</h2>
    <form name='form1' id=addrecipe>
         <!--action='' method=post enctype='multipart/form-data'-->
        <table>
            <tr>
                <td>
                    <INPUT type=submit id=submit name=save value=Save class=btn>
                </td>
                <td>
                    <a href=display.php><img src='images/display.jpg' style='border: none;'></a>
                </td>
            </tr>
        </table>
        <br>
        <div id='msgbox' style="color:#9B2507;font-size:15px;text-align:left;height:auto;display: none;"></div>
        <br>
        <div class=info>
            Fields Marked With an * are mandatory.<br>
            All dropdown/selection boxes on this page (except for Rating) are editable and will filter/autocomplete based on any letter/s typed in <br>
            the editable area (be patient if your selection list is long!!). You can also add new entries, just by typing them in. <br>
            Please ensure you receive a message to indicate the new value has been saved, before saving the recipe. If you don't, try pressing enter <br>
            or clicking elsewhere on the page to trigger the process.<br><br>
        </div>
        <a href='#' class=hideinfo>Hide Informational Text</a>
        <a href='#' class=showinfo style='display:none'>Show Informational Text</a>
        <br>
        <br>
        <?PHP
            $dbratings = pg_query($connection, "SELECT rating, image FROM rating ORDER BY id");  //return all ratings from db
            $dbdiet = pg_query($connection, "SELECT get_diet(diet) as diet FROM diet_owner where owner=$uid ORDER BY diet");//return all diets from db
            $dbunit = pg_query($connection, "SELECT get_unit(unit) as unit FROM unit_owner where owner=$uid ORDER BY unit");//return all units from db
            $dbing = pg_query($connection, "SELECT get_ingredient(ingredient) as ingredient FROM ingredient_owner where owner=$uid ORDER BY ingredient");//return all ingredients from db
            $dbpp = pg_query($connection, "SELECT get_preprep(preprep) as preprep FROM preprep_owner where owner=$uid ORDER BY preprep");//return all preparation methods from db
            $dbcat = pg_query($connection, "SELECT get_category(category) as category FROM category_owner where category != 20 and owner=$uid ORDER BY category");//return all categories from db
            $dbscat = pg_query($connection, "SELECT get_subcategory(subcategory) as subcategory FROM subcategory_owner where subcategory != 32 and owner=$uid ORDER BY subcategory");//return all subcategories from db
            $dbsource = pg_query($connection, "SELECT get_source(source) as source FROM source_owner where owner=$uid ORDER BY source");//return all sources from db
            $dbrecipe = pg_query($connection, "SELECT id, name FROM recipe where owner=$uid ORDER BY name");  //return all recipes from db
            $dbcuisine = pg_query($connection, "SELECT get_cuisine(cuisine) as cuisine FROM cuisine_owner where owner=$uid ORDER BY cuisine"); //return all cuisines from db
            $dbyield_unit = pg_query($connection, "SELECT get_yield_unit(yield_unit) as yield_unit FROM yield_unit_owner where owner=$uid ORDER BY yield_unit"); //return all yield_units from db
        ?>
        <table border=0 cellpadding = 2 cellspacing = 1>
            <tr>
                <td>
                    <strong>Name*</strong>
                </td>
                <td>
                    <input id=name type=text style='width:300px;' name='name' <?PHP if($_POST['name']) {print(" value=".'"'.stripslashes(stripslashes($_POST['name'])).'"');} ?>>
                </td>
            </tr>           
            
            <tr>
                <td>
                    <strong>Measurement System</strong>
                </td>
                <td>
                    <?PHP
                        $dbms = pg_query($connection, "SELECT get_measure(measure) as measure FROM measure_owner where get_owner(owner)='$user' ORDER BY measure");
                        $selms=$_POST['measure'];
                        if ($selms) {
                            print("<select id=measure name=measure>");
                            print("<option selected>$selms</option>");
                        } else {
                            print("<select id=measure name=measure>");
                            print("<option></option>");
                        }
                        for ($lt = 0; $lt < pg_num_rows($dbms); $lt++) {
                            $ms = pg_result($dbms, $lt, 0);
                            if ($selms!=$ms) {
                                print("<option>$ms</option>");
                            }
                        }
                    ?>
                    </select>
                    <script>
                        var m=dhtmlXComboFromSelect('measure');
                        m.enableOptionAutoHeight(true);
                        m.attachEvent("onChange",function(){
                            var value = m.getActualValue();
                            var field = "measure";
                            if (value!='')
                            var loader = dhtmlxAjax.postSync("ajax.php","field="+field+"&othervalue="+value);   
                        })
                    </script>
                </td>
            </tr>
        </table>
        <?php
            for ($lt1 = 0; $lt1 < 4; $lt1++) {
                unset($selcategory);
                unset($selsubcategory);
 
                if ($lt1 == 0) {
                    print("<table><tr width=100><td><strong>Category*</strong><br>");
                } else {
                    print("<table><tr><td>\n");
                }
                $selcategory = $_POST["cat$lt1"];
                if ($selcategory) {
                    print("<select id=cat$lt1 name=cat$lt1>\n<option selected>$selcategory</option>");
                } else {
                    print("<select id=cat$lt1 name=cat$lt1>\n<option></option>\n");
                }
                for ($lt = 0; $lt < pg_num_rows($dbcat); $lt++) {
                        $cat = pg_result($dbcat, $lt, 0);
                        if ($selcategory!=$cat) {
                            print("<option>$cat</option>\n");
                        }
                }
                echo '</select>';
                echo '<script>';
                echo '
                    function outputResponseC(loader){
                        if(loader.xmlDoc.responseText) {
                        alert("New Category Added");
                    }}';
                print("var cat$lt1=dhtmlXComboFromSelect(\"cat$lt1\");");
                print("cat$lt1.enableFilteringMode(true);");
                print("
                    dhtmlxEvent(cat$lt1.DOMelem,\"click\",function(){
                        cat$lt1._last=(new Date()).valueOf();
                    })
                    cat$lt1.attachEvent(\"onOpen\",function(){
                        window.setTimeout(function(){
                            if ((new Date()).valueOf()-(cat$lt1._last||0) > 100) return;
                            var text = cat$lt1.getComboText();
                            cat$lt1.setComboText(\"\");
                            cat$lt1.filterSelf();
                            cat$lt1.setComboText(text);
                        },1);
                    })
                    cat$lt1.attachEvent(\"onChange\",function(){
                        var value = cat$lt1.getActualValue();
                        var field = 'category';
                        if (value!='')
                        dhtmlxAjax.post('ajax.php','field='+field+'&othervalue='+value,outputResponseC);
                    })
                ");
                echo '</script>';
                echo '</td>';   
                if ($lt1 == 0) {
                    print("<td><strong>Subcategory</strong><br>");
                } else {
                    print("<td>");
                }
                $selsubcategory = $_POST["scat$lt1"];
                if ($selsubcategory) {
                    print("<select id=scat$lt1 name=scat$lt1><option selected>$selsubcategory</option>");
                } else {
                    print("<select id=scat$lt1 name=scat$lt1><option></option>");
                }
                for ($lt = 0; $lt < pg_num_rows($dbscat); $lt++) {
                        $scat = pg_result($dbscat, $lt, 0);
                        if ($selsubcategory!=$scat) {
                            print("<option>$scat</option>");
                        }
                }
                echo '</select>';
                echo '<script>';
                echo '
                    function outputResponseSC(loader){
                        if(loader.xmlDoc.responseText) {
                        alert("New Subcategory Added");
                    }}';
                print("var sc$lt1=dhtmlXComboFromSelect(\"scat$lt1\");");
                print("sc$lt1.enableFilteringMode(true);");
                print("
                    dhtmlxEvent(sc$lt1.DOMelem,\"click\",function(){
                        sc$lt1._last=(new Date()).valueOf();
                    })
                    sc$lt1.attachEvent(\"onOpen\",function(){
                        window.setTimeout(function(){
                            if ((new Date()).valueOf()-(sc$lt1._last||0) > 100) return;
                            var text = sc$lt1.getComboText();
                            sc$lt1.setComboText(\"\");
                            sc$lt1.filterSelf();
                            sc$lt1.setComboText(text);
                        },1);
                    })
                    sc$lt1.attachEvent(\"onChange\",function(){
                        var value = sc$lt1.getActualValue();
                        var field = 'subcategory';
                        if (value!='')
                        dhtmlxAjax.post('ajax.php','field='+field+'&othervalue='+value,outputResponseSC);
                    })      
                ");
                echo '</script>';
                echo '</td></tr></table>';
            }
            if ($_POST['ing']) {
                print ("<div id='paste_ing'>");
            } else {
                print ("<div id='paste_ing' style='display:none;'>");
            }
            ?>
            <table style='width: 100%;'>
                <tr>
                    <br><strong>Ingredients*</strong>
                    <div  class=info>
                        Format quantity unit ingredient; preprep, preprep,...<br>
                        Unit is mandatory.<br>
                        Please don't use any spaces in quantities e.g 1 1/2 should be replaced with 1.5<br>
                        Prefix any headers with '**' e.g. **Sauce<br>
                    </div>
                    <br><TEXTAREA id=ing name=ing><?php if($_POST['ing']) {print($_POST['ing']);}?></TEXTAREA>
                </tr>
            </table>
            </div>
            
            <?php
            if ($_POST['ing']) {
                print ("<a href='#' id=hshowman>Add ingredients one at a time</a><br>");
                print ("<div id='man_ing' style='display:none;'>");
            } else {
                print ("<a href='#' id=hshowman style='display:none;'>Add ingredients one at a time</a><br>");
                print ("<div id='man_ing'>");
            }
            ?>
            <?php
                if ($_POST['ing']) {
                    print ("<a href='#' id=hshowing style='display:none;'>Paste all ingredients at once</a><br>");
                } else {
                    print ("<br><a href='#' id=hshowing >Paste all ingredients at once</a><br>");
                }
            ?>
            <div class=info>
                Define ingredient headers by entering an ingredient prefixed with '**' e.g. **Sauce
            </div>
            <?php
            $ct=0;
            for ($lt1 = 0; $lt1 < 20; $lt1++) {
                $ct++;
                unset($selquantity);
                unset($selunit);
                unset($seling);
                unset($selpp);
                unset($selpp2);
                
                $selquantity = $_POST["qty$lt1"];
                $selunit = $_POST["unit$lt1"];
                $seling = $_POST["ing$lt1"];
                $selpp = $_POST["pp1$lt1"];
                $selpp2 = $_POST["pp2$lt1"];
                
                if ($lt1 == 0) {
                    print("<table><tr>");
                    if ($selquantity) {
                        print("<td><strong>Quantity</strong><br><input type=text id=qty$lt1 name=qty$lt1 class=smallinp value=".$selquantity.">");
                    } else {
                        print("<td><strong>Quantity</strong><br><input type=text id=qty$lt1 name=qty$lt1 class=smallinp value=''>");
                    }
                    if ($selunit) {
                        print("<td><strong>Unit</strong><br><select id=unit$lt1 name=unit$lt1><option selected>$selunit</option>");
                    } else {
                        print("<td><strong>Unit</strong><br><select id=unit$lt1 name=unit$lt1><option></option>");
                    }
                    for ($lt = 0; $lt < pg_num_rows($dbunit); $lt++) {
                        $unit = pg_result($dbunit, $lt, 0);
                        if ($unit!=$selunit) {
                            print("<option>$unit</option>");
                        }
                    }
                    print("</select>");
                } else {
                    print("<table><tr>");
                    if ($selquantity) {
                        print("<td><input type=text id=qty$lt1 name=qty$lt1 class=smallinp value=".$selquantity.">");
                    } else {
                        print("<td><input type=text id=qty$lt1 name=qty$lt1 class=smallinp value=''>");
                    }
                    
                    if ($selunit) {
                        print("<td><select name=unit$lt1 id=unit$lt1><option selected>$selunit</option>");
                    } else {
                        print("<td><select name=unit$lt1 id=unit$lt1><option></option>");
                    }
                    for ($lt = 0; $lt < pg_num_rows($dbunit); $lt++) {
                        $unit = pg_result($dbunit, $lt, 0);
                        if ($unit!=$selunit) {
                            print("<option>$unit</option>");
                        }
                    }
                    echo '</select>';
                }
                echo '<script>';
                echo '
                    function outputResponseU(loader){
                        if(loader.xmlDoc.responseText) {
                        alert("New Unit Added");
                    }}
                ';
                print("var u$lt1=dhtmlXComboFromSelect(\"unit$lt1\");");
                print("u$lt1.enableFilteringMode(true);");
                print("
                    dhtmlxEvent(u$lt1.DOMelem,\"click\",function(){
                        u$lt1._last=(new Date()).valueOf();
                    })
                    u$lt1.attachEvent(\"onOpen\",function(){
                        window.setTimeout(function(){
                            if ((new Date()).valueOf()-(u$lt1._last||0) > 100) return;
                            var text = u$lt1.getComboText();
                            u$lt1.setComboText(\"\");
                            u$lt1.filterSelf();
                            u$lt1.setComboText(text);
                        },1);
                    })
                    u$lt1.attachEvent(\"onChange\",function(){
                        var value = u$lt1.getActualValue();
                        var field = 'unit';
                        if (value!='')
                        dhtmlxAjax.post('ajax.php','field='+field+'&othervalue='+value,outputResponseU);
                    })
                ");
                echo '</script>';
                
                if ($lt1 == 0) {
                    print("<td><strong>Ingredient*</strong><br>");
                } else {
                    print("<td>");
                }
                if ($seling) {
                    print("<select name=ing$lt1 id=ing$lt1><option selected>$seling</option>");
                } else {
                    print("<select name=ing$lt1 id=ing$lt1><option></option>");
                }
                for ($lt = 0; $lt < pg_num_rows($dbing); $lt++) {
                    $ingv = pg_result($dbing, $lt, 0);
                    if ($ingv!=$seling) {
                        print("<option>$ingv</option>");
                    }
                }
                echo '</select>';
                echo '<script>';
                echo '
                    function outputResponseI(loader){
                        if(loader.xmlDoc.responseText) {
                        alert("New Ingredient Added");
                    }}';
                print("var i$lt1=dhtmlXComboFromSelect(\"ing$lt1\");");
                print("i$lt1.enableFilteringMode(true);");
                print("
                    dhtmlxEvent(i$lt1.DOMelem,\"click\",function(){
                        i$lt1._last=(new Date()).valueOf();
                    })
                    i$lt1.attachEvent(\"onOpen\",function(){
                        window.setTimeout(function(){
                            if ((new Date()).valueOf()-(i$lt1._last||0) > 100) return;
                            var text = i$lt1.getComboText();
                            i$lt1.setComboText(\"\");
                            i$lt1.filterSelf();
                            i$lt1.setComboText(text);
                        },1);
                    })
                    i$lt1.attachEvent(\"onChange\",function(){
                        var value = i$lt1.getActualValue();
                        var field = 'ingredient';
                        if (value!='')
                        dhtmlxAjax.post('ajax.php','field='+field+'&othervalue='+value,outputResponseI);
                    })
                ");
                echo '</script>';
                echo '</td>';
                if ($lt1 == 0) {
                    print("<td><strong>Preparation</strong><br>");
                } else {
                    print("<td>");
                }
                if ($selpp) {
                    print("<select name=pp1$lt1 id=pp1$lt1><option selected>$selpp</option>");
                } else {
                    print("<select name=pp1$lt1 id=pp1$lt1><option></option>");
                }
                for ($lt = 0; $lt < pg_num_rows($dbpp); $lt++) {
                    $pp = pg_result($dbpp, $lt, 0);
                    if ($pp!=$selpp) {
                        print("<option>$pp</option>");
                    }
                }
                echo '</select>';
                echo '<script>';
                echo '
                    function outputResponsePP1(loader){
                        if(loader.xmlDoc.responseText) {
                        alert("New Preparation Method Added");
                    }}';
                print("var p$lt1=dhtmlXComboFromSelect(\"pp1$lt1\");");
                print("p$lt1.enableFilteringMode(true);");
                print("
                    dhtmlxEvent(p$lt1.DOMelem,\"click\",function(){
                        p$lt1._last=(new Date()).valueOf();
                    })
                    p$lt1.attachEvent(\"onOpen\",function(){
                        window.setTimeout(function(){
                            if ((new Date()).valueOf()-(p$lt1._last||0) > 100) return;
                            var text = p$lt1.getComboText();
                            p$lt1.setComboText(\"\");
                            p$lt1.filterSelf();
                            p$lt1.setComboText(text);
                        },1);
                    })
                    p$lt1.attachEvent(\"onChange\",function(){
                        var value = p$lt1.getActualValue();
                        var field = 'preprep';
                        if (value!='')
                        dhtmlxAjax.post('ajax.php','field='+field+'&othervalue='+value,outputResponsePP1);
                    })
                ");
                echo '</script>';
                echo '</td>';
                if ($lt1 == 0) {
                    print("<td><strong>Preparation</strong><br>");
                } else {
                    print("<td>");
                }
                if ($selpp2) {
                    print("<select name=pp2$lt1 id=pp2$lt1><option selected>$selpp2</option>");
                } else {
                    print("<select name=pp2$lt1 id=pp2$lt1><option></option>");
                }
                for ($lt = 0; $lt < pg_num_rows($dbpp); $lt++) {
                    $pp2 = pg_result($dbpp, $lt, 0);
                    if ($pp2!=$selpp2) {
                        print("<option>$pp2</option>");
                    }
                }
                echo '</select>';
                echo '<script>';
                echo '
                    function outputResponsePP2(loader){
                        if(loader.xmlDoc.responseText) {
                        alert("New Preparation Method Added");
                    }}';
                print("var pp$lt1=dhtmlXComboFromSelect(\"pp2$lt1\");");
                print("pp$lt1.enableFilteringMode(true);");
                print("
                    dhtmlxEvent(pp$lt1.DOMelem,\"click\",function(){
                        pp$lt1._last=(new Date()).valueOf();
                    })
                    pp$lt1.attachEvent(\"onOpen\",function(){
                        window.setTimeout(function(){
                            if ((new Date()).valueOf()-(pp$lt1._last||0) > 100) return;
                            var text = pp$lt1.getComboText();
                            pp$lt1.setComboText(\"\");
                            pp$lt1.filterSelf();
                            pp$lt1.setComboText(text);
                        },1);
                    })
                    pp$lt1.attachEvent(\"onChange\",function(){
                        var value = pp$lt1.getActualValue();
                        var field = 'preprep';
                        if (value!='')
                        dhtmlxAjax.post('ajax.php','field='+field+'&othervalue='+value,outputResponsePP2);
                    })
                ");
                echo '</script>';
                echo '</td>';
                echo '</tr></table>';
            }
        ?>
        </div>
        <br>
        <strong>Directions*</strong>
        <div class=info>
            Here's the character for degrees celsius and fahrenheit if you need them &#8451 &#8457
        </div>
        <br><TEXTAREA id='directions' name='directions'><?php if ($_POST['directions']) {print(stripslashes($_POST['directions']));} else if ($directions) {print($directions);}?></TEXTAREA><br>
        <strong>Notes</strong>
        <br><TEXTAREA id=note style='height:30px;' name='note'><?php if ($_POST['note']) {print($_POST['note']);} else if ($note) {print($note);}?></TEXTAREA><br><br>
        <table border=0 cellpadding = 2 cellspacing = 1>
            <tr>
                <td>
                    <strong>Source</strong>
                </td>
                <td>
                    <?php
                        if ($_POST['source']) {$selsource=$_POST['source'];} //if item already selected trap value
                        if ($selsource) {
                            print("<select name='source' id='source'><option selected>$selsource</option>");
                        } else {
                            print("<select name='source' id='source'><option></option>");
                        }
                        for ($lt = 0; $lt < pg_num_rows($dbsource); $lt++) {
                            $src = pg_result($dbsource, $lt, 0);
                            if ($src!=$selsource) {
                                print("<option>$src</option>");
                            }
                        }
                    ?>
                    </select>
                    <script>
                        function outputResponseSRC(loader){
                            if(loader.xmlDoc.responseText) {
                            alert("New Source Added");
                        }}
                        var src=dhtmlXComboFromSelect("source");
                        src.enableFilteringMode(true);
                        dhtmlxEvent(src.DOMelem,"click",function(){
                            src._last=(new Date()).valueOf();
                        })
                        src.attachEvent("onOpen",function(){
                            window.setTimeout(function(){
                                if ((new Date()).valueOf()-(src._last||0) > 100) return;
                                var text = src.getComboText();
                                src.setComboText("");
                                src.filterSelf();
                                src.setComboText(text);
                            },1);
                        })
                        src.attachEvent("onChange",function(){
                            var value = src.getActualValue();
                            var field = 'source';
                            if (value!='')
                            dhtmlxAjax.post('ajax.php','field='+field+'&othervalue='+value,outputResponseSRC);
                        })
                    </script>
                </td>
                <td>
                    <strong>Rating</strong>
                </td>
                <td>
                    <?PHP
                        if ($_POST['rating']) {$selrating=$_POST['rating'];} //if item already selected trap value
                        if ($selrating) {
                            for ($lt = 0; $lt < pg_num_rows($dbratings); $lt++) {
                                if ($selrating == pg_result($dbratings, $lt, 0)) {
                                    $rti = substr(pg_result($dbratings, $lt, 1), 0, (strlen (pg_result($dbratings, $lt, 1))) - (strlen (strrchr(pg_result($dbratings, $lt, 1),'.'))));
                                }
                                
                            }
                            print("<select style='width:100px;' name=rating id=rating><option selected img_src='images/".$rti."_sm.gif'>$selrating</option>");
                        } else{
                            print("<select style='width:100px;' name=rating id=rating>");
                        }
                        
                        for ($lt = 0; $lt < pg_num_rows($dbratings); $lt++) {
                            $rt = pg_result($dbratings, $lt, 0);
                            $rti = substr(pg_result($dbratings, $lt, 1), 0, (strlen (pg_result($dbratings, $lt, 1))) - (strlen (strrchr(pg_result($dbratings, $lt, 1),'.'))));
                            //$rti = pg_result($dbratings, $lt, 1);
                            if ($rt!=$selrating) {
                                print("<option img_src='images/".$rti."_sm.gif'>$rt</option>");
                            }
                        }
                        echo '</select>';
                    ?>
                    <script>
                        var r=dhtmlXComboFromSelect('rating');
                        r.enableOptionAutoHeight(true);
                        r.readonly(true);
                    </script>
                </td>
                <td>
                    <strong>Tried</strong>
                </td>
                <td>
                    <input class=chk type=checkbox id=tried name='tried' <?php if($_POST['tried']=='Yes') {print(" CHECKED");} ?>>
                    
                </td>
            </tr>
            <tr>
                <td>
                    <strong>Cuisine</strong>
                </td>
                <td>
                    <?PHP
                        if ($_POST['cuisine']) {$selcuisine=$_POST['cuisine'];} //if item already selected trap value
                        if ($selcuisine) {
                            print("<select name=cuisine id=cuisine><option selected>$selcuisine</option>");
                        } else {
                            print("<select name=cuisine id=cuisine><option></option>");
                        }
                        for ($lt = 0; $lt < pg_num_rows($dbcuisine); $lt++) {
                            $cuisine = pg_result($dbcuisine, $lt, 0);
                            if ($cuisine!=$selcuisine) {
                                print("<option>$cuisine</option>");
                            }
                        }
                        echo '</select>';
                    ?>
                    <script>
                        function outputResponseCUS(loader){
                            if(loader.xmlDoc.responseText) {
                            alert("New Cuisine Added");
                        }}
                        var cus=dhtmlXComboFromSelect("cuisine");
                        cus.enableFilteringMode(true);
                        dhtmlxEvent(cus.DOMelem,"click",function(){
                            cus._last=(new Date()).valueOf();
                        })
                        cus.attachEvent("onOpen",function(){
                            window.setTimeout(function(){
                                if ((new Date()).valueOf()-(cus._last||0) > 100) return;
                                var text = cus.getComboText();
                                cus.setComboText("");
                                cus.filterSelf();
                                cus.setComboText(text);
                            },1);
                        })
                        cus.attachEvent("onChange",function(){
                            var value = cus.getActualValue();
                            var field = 'cuisine';
                            if (value!='')
                            dhtmlxAjax.post('ajax.php','field='+field+'&othervalue='+value,outputResponseCUS);
                        })
                    </script>
                </td>
                <td>
                    <strong>Makes</strong>
                </td>
                <td>
                    <input class=smallinp type=text id=yield name='yield' <?PHP if($_POST['yield']) {print("value='".$_POST['yield']."'");} ?>>
                    <?PHP
                        if ($_POST['yield_unit']) {$selyield_unit=$_POST['yield_unit'];} //if item already selected trap value
                        if ($selyield_unit) {
                            print("<select name=yield_unit id=yield_unit><option selected>$selyield_unit</option>");
                        } else {
                            print("<select name=yield_unit id=yield_unit><option></option>");
                        }
                        for ($lt = 0; $lt < pg_num_rows($dbyield_unit); $lt++) {
                            $yield_unit = pg_result($dbyield_unit, $lt, 0);
                            if ($yield_unit!=$selyield_unit) {
                                print("<option>$yield_unit</option>");
                            }
                        }
                        echo '</select>';
                    ?>
                    <script>
                        function outputResponsey(loader){
                            if(loader.xmlDoc.responseText) {
                            alert("New Yield Unit Added");
                        }}
                        var y=dhtmlXComboFromSelect("yield_unit");
                        y.enableFilteringMode(true);
                        dhtmlxEvent(y.DOMelem,"click",function(){
                            y._last=(new Date()).valueOf();
                        })
                        y.attachEvent("onOpen",function(){
                            window.setTimeout(function(){
                                if ((new Date()).valueOf()-(y._last||0) > 100) return;
                                var text = y.getComboText();
                                y.setComboText("");
                                y.filterSelf();
                                y.setComboText(text);
                            },1);
                        })
                        y.attachEvent("onChange",function(){
                            var value = y.getActualValue();
                            var field = 'yield_unit';
                            if (value!='')
                            dhtmlxAjax.post('ajax.php','field='+field+'&othervalue='+value,outputResponsey);
                        })
                    </script>
                </td>
                <td>
                    <strong>Prep Time</strong>
                </td>
                <td>
                    <input class=smallinp type=text id=preptime name='preptime' value='<?php if ($_POST['preptime']) {print($_POST['preptime']);}?>'>
                    
                </td>
            </tr>
        </table>
        <table>
            <tr>
                <td>
                    <strong>Diet/s</strong><br>
                    <select id=diet name=diet[] multiple size=20 onChange='checkAdd(this)'>
                    <?PHP
                        $selrows = count($_POST['diet']);
                        $dselrows = 0;
                        while ($_POST["diet$dselrows"] != '') {
                            $dselrows++;
                        }
                        for ($lt = 0; $lt < pg_num_rows($dbdiet); $lt++) {
                            $dietval = pg_result($dbdiet, $lt, 0);
                            if (isset($_POST['diet'])) {
                                $match = '';
                                for ($r=0; $r < $selrows; $r++) {
                                    $selval = $_POST['diet'][$r];
                                    if ($selval == $dietval) {
                                        $match = 'yes';
                                        print("<OPTION SELECTED VALUE='$dietval'>$dietval</option>");
                                    } 
                                }
                                if (empty($match)) {
                                        print("<option>$dietval</option>");
                                }
                            } else if ($dselrows>0) {
                                $match = '';
                                for ($r=0; $r < $dselrows; $r++) {
                                    $selval = $_POST["diet$r"];
                                    if ($selval == $dietval) {
                                        $match = 'yes';
                                        print("<OPTION SELECTED VALUE='$dietval'>$dietval</option>");
                                    } 
                                }
                                if (empty($match)) {
                                        print("<option>$dietval</option>");
                                }
                            } else {
                                print("<option>$dietval</option>");
                            }
                        }
                    ?>  
                    <option>Other</option></select>
                    <!--<script>
                        function outputResponsey(loader){
                            if(loader.xmlDoc.responseText) {
                            alert("New Diet Added");
                        }}
                        var d=dhtmlXComboFromSelect("diet");
                        d.enableFilteringMode(true);
                        dhtmlxEvent(d.DOMelem,"click",function(){
                            d._last=(new Date()).valueOf();
                        })
                        d.attachEvent("onOpen",function(){
                            window.setTimeout(function(){
                                if ((new Date()).valueOf()-(d._last||0) > 100) return;
                                var text = d.getComboText();
                                d.setComboText("");
                                d.filterSelf();
                                d.setComboText(text);
                            },1);
                        })
                        d.attachEvent("onChange",function(){
                            var value = d.getActualValue();
                            var field = 'diet';
                            if (value!='')
                            dhtmlxAjax.post('ajax.php','field='+field+'&othervalue='+value,outputResponsey);
                        })
                    </script>-->
                </td>
                    <td>
                        <strong>Related Recipe/s</strong><br>
                        <select id=related_recipe name=related_recipe[] multiple size=20'>
                        <?PHP
                            unset($selrows);
                            $selrows = count($_POST['related_recipe']);
                            $rselrows = 0;
                            while ($_POST["rel$rselrows"] != '') {
                                $rselrows++;
                            }
                            for ($lt = 0; $lt < pg_num_rows($dbrecipe); $lt++) {
                                $recipeval = pg_result($dbrecipe, $lt, 1);
                                if (isset($_POST['related_recipe'])) {
                                    $match = '';
                                    for ($r=0; $r < $selrows; $r++) {
                                        $selval = $_POST['related_recipe'][$r];
                                        if ($selval == $recipeval) {
                                            $match = 'yes';
                                            print("<OPTION SELECTED VALUE='$recipeval'>$recipeval</option>");
                                        } 
                                    }
                                    if (empty($match)) {
                                            print("<option>$recipeval</option>");
                                    }
                                } else if ($rselrows>0) {
                                    $match = '';
                                    for ($r=0; $r < $rselrows; $r++) {
                                        $selval = $_POST["rel$r"];
                                        if ($selval == $recipeval) {
                                            $match = 'yes';
                                            print("<OPTION SELECTED VALUE='$recipeval'>$recipeval</option>");
                                        } 
                                    }
                                    if (empty($match)) {
                                            print("<option>$recipeval</option>");
                                    }
                                }else {
                                    print("<option>$recipeval</option>");
                                }
                            }
                        ?>
                        </select>
                    </td>
                </tr>
            </table>
            <div class=info>
                Use CTRL/SHIFT to select multiples in the 2 selection boxes above.<br>
                To unselect an item press CTRL, then click on the item.<br><br>
            </div>
            <table>
            <tr>
                <td valign=top>
                    <strong>Image</strong>
                </td>
                <td>
                <input name='imagefl' id='imagefl' size='22.5' class='fle' type='file'><br>
                <div class=info>Please ensure your image names don't contain any special characters like %</div>
                <br>
                <span id="progress1"></span>
                <div class=image id='imagedisp'>
                <?php
                    if($_POST['newimage']) {
                        if($id) {
                            print('<img src="images/recipe/'.$user.'-'.$_POST['newimage'].'"><br><a id=hideimg href="#">Hide image</a>&nbsp;<a id=remimg href="#">Remove image</a></div><input id=image name=image type=hidden value="'.$_POST['newimage'].'">');
                        } else {
                            print('<img src="imagetmp/'.$_POST['newimage'].'"><br><a id=hideimg href="#">Hide image</a>&nbsp;<a id=remimg href="#">Remove image</a></div><input name=image id=image type=hidden value="'.$_POST['newimage'].'">');
                        }
                    } else if($_POST['image']) {
                        if($id) {
                            print('<img src="images/recipe/'.$_POST['image'].'"><br><a id=hideimg href="#">Hide image</a>&nbsp;<a id=remimg href="#">Remove image</a></div><input id=image name=image type=hidden value="'.$_POST['image'].'">');
                        } else {
                            print('<img src="imagetmp/'.$_POST['image'].'"><br><a id=hideimg href="#">Hide image</a>&nbsp;<a id=remimg href="#">Remove image</a></div><input id=image name=image type=hidden value="'.$_POST['image'].'">');
                            
                        }
                    }
                ?>
                </div>
                <a href="#" id='showimg' style='display:none'>Show image</a>
            </td>
            </tr>
            </table>
            <table>
                <tr>
                    <td>
                        <INPUT type=submit id=submit name=save value=Save class=btn>
                    </td>
                    <td>
                        <a href=display.php><img src='images/display.jpg' style='border: none;'></a>
                    </td>
                </tr>
            </table>
            <br>
            <div id='msgbox1' style="color:#9B2507;font-size:15px;text-align:left;display: none;"></div>
            <input type=HIDDEN id=id name=id value=<?php if($_POST['cbut_val']!='Copy' and $_POST['bcbut_val']!='Copy') {echo $id;}?>>
            <input type=HIDDEN name=added id=added value=<?php if($_POST['cbut_val']!='Copy' and $_POST['bcbut_val']!='Copy') {echo $added;} ?>>
        </FORM>
    </td>
</tr>
<?php require_once('bottom.php'); ?>
 
 
 

Re: Advice needed on getting large page to load quicker

Posted: Mon Sep 21, 2009 5:48 pm
by Eric!
I agree the queries are probably the killer. Can you generate a static html version of the form and just include it when rendering the page? The static form would only need to be generated when the fields of the database form are changed. You could create a form version number that updates when the database is modified in such a way that the form would be changed. You could then check the static form's version number with the database and regenerate the form only when updates occur.

Re: Advice needed on getting large page to load quicker

Posted: Mon Sep 21, 2009 7:34 pm
by barb woolums
Thanks for the suggestion, but I think the database gets updated too often for this aproach to help much.

Re: Advice needed on getting large page to load quicker

Posted: Tue Sep 22, 2009 4:45 am
by robnet

Code: Select all

$id = $_POST['id'];
You probably want to think about sanitizing your user input here, rather than just trusting that your user isn't going to post something like this:

Code: Select all

1;DROP TABLE recipe;
But back to the optimization issue; you can probably save a fair amount of time by bringing most of your select queries into one using joins. Though this is where I bow out since I would probably only point you in the wrong direction from here!

Re: Advice needed on getting large page to load quicker

Posted: Tue Sep 22, 2009 6:38 am
by barb woolums
Even if id is stored in a hidden field?

Re: Advice needed on getting large page to load quicker

Posted: Tue Sep 22, 2009 7:04 am
by robnet
barb woolums wrote:Even if id is stored in a hidden field?
Yes, definitely. The user has complete control of the web browser and can modify your html before sending anything. Using the right plugin for firefox or most other current browsers you can post whatever data you want to any web page, regardless of what is in the original form.

Re: Advice needed on getting large page to load quicker

Posted: Tue Sep 22, 2009 1:32 pm
by Christopher
I think you should look in to the JOIN functionality in SQL.

Re: Advice needed on getting large page to load quicker

Posted: Tue Sep 22, 2009 4:04 pm
by josh
The issue seems to be that you have a single result set you are going to display from multiple places and you are querying each time you display it?

The solution would be to separate your presentation from your model, so you would load up your 'phenomenon' object ( weight for instance ) so you would have $weight
You would grab this via singleton static access from the viewscript, or preferably you would assign it to your viewscript from a controller [1].
In this weight class you would do 1 query in the constructor and store it's results in an object property, or statically "on the class".
Once you have the weight class or object you can ask it ->getData() or whatever, all querying is done 1x and ->getData() simply returns the array that has been stored, as long as you only construct this object 1x you will cut back on duplicating queries

Or to state it in simpler procedural terms, yes do the query once, store it in a variable ( array for example ) and use that same result set for all 20 of your drop downs. I recommend looking into various forms of ORM ( object relational mappers ) which automate this with "identity maps" ( although not many of them are able to detect duplicate queries, some degree of careful coding is almost always needed )

[1] model view controller

Re: Advice needed on getting large page to load quicker

Posted: Tue Sep 22, 2009 9:02 pm
by barb woolums
Seems I now have 2 issues here.

Robnet - how would I go about preventing this?

Josh - I am only doing the query for each dropdown once, and then looping through the resultset 20 times to build each dropdown. Are you saying that it would be quicker to build an array for each resultset and loop through that instead to build the dropdowns, or am I completely missing the point?

Re: Advice needed on getting large page to load quicker

Posted: Wed Sep 23, 2009 4:03 am
by robnet
A quick search pulls up this resource which, after skimming through, looks pretty good. Make sure you read the lot - especially the database security bit, halfway down the page.

Re: Advice needed on getting large page to load quicker

Posted: Wed Sep 23, 2009 6:23 am
by barb woolums
Thanks so much for your advice and help - I had no idea what malicious people could do, and I really appreciate it.

The article looks really good, and I will read all of it and implement the sanity check on all my forms.

Re: Advice needed on getting large page to load quicker

Posted: Wed Sep 23, 2009 10:20 am
by pickle
I'm not completely sure the delay is the queries. I've had some pages where the vast majority of page load time is the transmission of text and parsing by the browser. If you're looping through a resultset 80 times, and each resultset could have lots of rows - that's a lot of time to iterate through the resultset, and to transmit that to the browser.

Iterating through the same resultset multiple times is the first thing I'd look at. If the only difference is the name of the <select>, you could approach it this way:

Code: Select all

$select = '<select name = "%NAME%">';
while($row = pg_fetch_assoc($resultset)
{
    $select .= '<option value = "'.$row['value'].'">'.$row['human_readable'].'</option>';
}
$select .= '</select>';
 
//then, when you're outputing that select box 80 times
echo str_replace('%NAME%','unique_name_for_this_select',$select);
It might be useful to do some benchmarking to determine where the lion's share of time is being eaten up:

Code: Select all

<?php
//beginning of file
$start_time = microtime(TRUE);
 
//after the queries are done
$query_time = microtime(TRUE);
 
//after the output is generated
$end_time = microtime(TRUE);
 
echo 'Query duration: '.$query_time - $start_time.'<br />';
echo 'Output generation duration: '.$end_time - $query_time;

Re: Advice needed on getting large page to load quicker

Posted: Thu Sep 24, 2009 3:38 am
by josh
barb woolums wrote: Josh - I am only doing the query for each dropdown once, and then looping through the resultset 20 times to build each dropdown. Are you saying that it would be quicker to build an array for each resultset and loop through that instead to build the dropdowns, or am I completely missing the point?
Yes, you are executing one query for each dropdown. You want to execute one query for the whole request. Either the array or http://us2.php.net/mysql_data_seek will help you re-structure that coding strategy. Looping thru a result-set does not re-run the query, but if you are calling mysql_query 20 times that is undesired.