PHP中页面上的持久变量

时间:2009-12-10 17:56:18

标签: php performance

在我正在处理的页面上,我有几个不同的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 个答案:

答案 0 :(得分:3)

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

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

您可以从查看Zend Framework中受益。对于学习PHP开发人员来说,它是一个很好的工具,可以查看有关如何完成许多事情的行业标准。

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

答案 1 :(得分:-1)

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