代码之家  ›  专栏  ›  技术社区  ›  Elliot

PHP中页面上的持久变量

  •  0
  • Elliot  · 技术社区  · 15 年前

    在我正在处理的一个页面上,我有几个不同的PHP片段,例如一个在头部处理动态JavaScript,一个在主体中用于表创建。但是,许多操作、SQL查询等在这两个区域之间是相同的。例如,我不得不一次又一次地重新连接到同一个数据库。有没有什么方法可以使代码流线型化,这样我就不需要进行如此多的重复和重复计算了?

    页面代码,尽管没有补充文件它看起来不太合适。而且,它很长。

    <!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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Our Phones</title>
    <style type="text/css">
    <!--
    #main #list table{
        font-family: Georgia, "Times New Roman", Times, serif;
        font-size: 12px;
        width: 750px;
        border-top-style: none;
        border-right-style: none;
        border-bottom-style: none;
        border-left-style: none;
    }
    
    #float_tot {
        font-family: Arial, Helvetica, sans-serif;
        font-size: 10px;
        color: #000;
        background-color: #FFF;
        overflow: auto;
        position: fixed;
        top: 127px;
        height: 150px;
        width: 198px;
        border: 2px groove #999;
        background-attachment: scroll;
    }
    
    .price {
        font-size: 16px;
        text-align: center;
    }
    .descr {
        width: 300px;
    }
    -->
    </style>
    <?php
    $con=mysql_connect(localhost,*****,*******);//connect to database
    mysql_select_db("phone_site",$con);//select table
    //work out the number of rows in the table
    $query="SELECT * FROM phones WHERE 1=1";//set an always true WHERE
    //search
    $min=$_REQUEST['min_price'];
    $max=$_REQUEST['max_price'];
    $manuf=$_REQUEST['manufact'];
    //if not empty, add them to the condition
    if (!empty($min)){
    $query.=" AND price>=$min";}
        if (!empty($max)){  
            $query.=" AND price<=$max";}
        if (!empty($manuf)){
            $query.=" AND manu='$manuf'";}
    $result=mysql_query($query);
    $num=mysql_num_rows($result);
    //prepare 2 substitutions
    $pass=NULL;//this will fill in the correct number of input variables
    $parse=NULL;//this will parse them into an array of ints.
    $prices=NULL;//this will generate the pricelist
    $i=0;
    while($data = mysql_fetch_array($result)){
        $parse.="D[$i]=parseInt(d$i);";
        $pass.="d$i, ";
        $prices.="P[$i]=" . $data['price'] . ";";
        $i++;
        }
    $passd=substr_replace($pass,"",-2);
    //make javascript
    print("<script type=\"text/javascript\">
    function total($passd){
        var D=new Array();
        $parse //parse the input into integers. if the field is blank 'NaN' should return.
        var P=new Array();
        $prices//prices.
        var total = 0;//set total to zero.
        for (i=0;i<$num;i++){
            if (D[i]){//only do something if the field is not blank
                total += D[i]*P[i];
            }//add D[i] number of that item at P[i] Price to the total
        }
        document.output.readout.value= (total);//output
    }
    </script>");
    mysql_close($con);
    ?>
    
    <link href="format.css" rel="stylesheet" type="text/css" />
    </head>
    
    <body>
    <div id="header">
        <img src="Images/Site/Banner.gif" width="1200" height="117" />
    </div>
    <div id="sidebar">
    <a href="index.php"><img src="Images/Site/Home.gif" width="208" height="48" alt="Home" /></a>
    <a href="phones.php"><img src="Images/Site/Phones.gif" width="208" height="58" alt="Phones" /></a>
    <a href="about.php"><img src="Images/Site/About.gif" width="208" height="51" alt="About" /></a>
    <img src="Images/Site/R_sibe_b.gif" width="208" height="56" />
    </div>
    
    <div id=endorse>
    <?php
    $quote=Null;
    $sign=Null;
    $afil=Null;
    $con=mysql_connect(localhost,****,*******);//connect to database
    mysql_select_db("phone_site",$con);//select table
    $query="SELECT * FROM quotes ORDER BY Rand() LIMIT 1";//get one random row
    $result=mysql_query($query);
    $data = mysql_fetch_array($result);//get data from location $result
        //print out text
        print ("<p id=\"quote\">" . $data['quote'] . "</p>");
        print ("<p id=\"ename\">" . $data['sign'] . "</p>");
        print ("<p id=\"afill\">--  " . $data['afil'] . "</p>");
    mysql_close($con);//close connection
    ?>
    </div>
    
    <div id="main">
    <?php
    $con=mysql_connect(localhost,******,********);//connect to database
    mysql_select_db("phone_site",$con);//select database
    //make maufacturer search
    $query="SELECT DISTINCT manu FROM phones";
    $result=mysql_query($query);
    $manl="<option value=''></option>";
    while($data = mysql_fetch_array($result)){
        $manl.="<option value=\"" . $data['manu'] . "\">" . $data['manu'] . "</option>";
    }
    print "<form name=\"search\" action=\"phones.php\" method=\"post\">
                Manufacturer?
            <select name=\"manufact\">
                $manl
            </select> <br/>
            What is your price range? $<input name=\"min_price\" type=\"text\" value =\"\" maxlength=\"6\" /> to $<input name=\"max_price\" type=\"text\" maxlength=\"6\" value=\"\"/>
            <input type=\"submit\" name=\"seek\"/>
        </form>
        <hr/>
    <div id=\"list\">
        <form name=\"phonelist\">
            <table><!--table populated using PHP/MYSQL-->
                <tr>
                    <th>&nbsp;</th><th>&nbsp;</th><th>Features</th><th>Price</th>
                </tr>";
    
    
    
                $query="SELECT * FROM phones WHERE 1=1";//set an always true WHERE
                //search
                $min=$_REQUEST['min_price'];
                $max=$_REQUEST['max_price'];
                $manuf=$_REQUEST['manufact'];
                //if not empty, add them to the condition
                if (!empty($min)){
                    $query.=" AND price>=$min";}
                if (!empty($max)){  
                    $query.=" AND price<=$max";}
                if (!empty($manuf)){
                    $query.=" AND manu='$manuf'";}
    
                $result=mysql_query($query);
                //work out the number of rows in the table
                $num=mysql_num_rows($result);
                //make the onkeyup list, giving it that many entries
                $hold="total(";
                for ($i=1;$i<=$num;$i++){
                    $hold.="phonelist.a$i.value, ";}
                $pass= substr_replace($hold,")",-2);
    
                //now print all the data in the table for population, subject to entered search strings
                $count=0;
                while($data = mysql_fetch_array($result)){//get data from location $result
                    $count++;
                    print("<tr>
                        <td><img src=\"Images/" . $data['image'] . "\" width=\"100\" /></td>
                        <td class=\"descr\">" . $data['blurb'] . "</td>
                        <td><ul>" . $data['features']. "</ul></td>
                        <td><span class=\"price\">\$" . $data['price'] . "</span><br/>
                        How many would you like? <br/>
                        <input name=\"a$count\" type=\"text\" maxlength=\"2\" onkeyup=\"$pass\" /></td>
                    </tr>");
                }
                mysql_close($con);
    
            print "</table>
        </form>
    </div>";
    ?>
    </div>
    
    <div id="lside">
            <div id="float_tot">
                <p>Your current total is</p>
                <br/>
                <form name="output">
                    $<input name="readout" type="text" readonly="readonly" value="0"/>
                </form>     
            </div>
    </div>
    
    <div id="footer">
        <img src="Images/Site/footer.gif" width="1200" height="74" />
    </div>
    </body>
    

    2 回复  |  直到 11 年前
        1
  •  3
  •   Brad    15 年前

    您可以在一个页面上反复重复使用变量。至少对于数据库连接来说,这是个好主意。只在页面顶部定义一次$con,并多次使用它。只因为关闭了php标记(?>)并不意味着你失去了变量。

    对于代码重用,我将研究为公共代码片段定义函数。理想情况下,您可以创建类来封装逻辑。例如,通常有一个数据库连接对象(或框架),它封装了连接、查询等。

    您可以从查看Zend框架中获益。对于学习PHP开发人员来说,它是一个很好的工具,可以了解行业标准,了解如何执行您要求的许多操作。

    http://framework.zend.com/docs/quickstart

        2
  •  -1
  •   troelskn    15 年前

    有几种方法可以在PHP中重用代码。最基本和最强大的是 functions .