2009-12-10 4 views
0

На странице, над которой я работаю, у меня есть несколько различных частей PHP, таких как один в голове для обработки динамического Javascript и один в основной части для создания таблицы. Однако многие операции, SQL-запросы и т. Д. Одинаковы между двумя областями. Например, мне постоянно приходится снова подключаться к одной и той же базе данных. Есть ли способ для меня упростить код, чтобы мне не нужно было много дублирования и повторных вычислений?Постоянные переменные на странице в PHP

Код страницы, хотя он не будет выглядеть правильно без дополнительных файлов. Кроме того, это очень долго.

<!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> 

+1

Для начала вам нужно только одно соединение mysql. Вы можете безопасно удалить любые избыточные ** $ con ** переменные в своем коде и использовать только первое соединение. Затем удалите все, кроме самого последнего ** mysql_close ($ con) **, чтобы открыть соединение для всей страницы. –

+0

Не совсем ответ, вот почему я просто комментирую: В общем, хорошо отделить php-код от html-кода. Таким образом, ваш PHP-код проще использовать повторно (что также решает вашу проблему). Брэд уже указал направо. Взгляните на Zend Framework. –

+0

+1, чтобы повторить голосование кого-то другого: НЕ ЗАГРУЗИТЕ-ГОЛОСОВАТЬ людей, не комментируя проголосовать. –

ответ

3

Вы можете повторно использовать переменные снова и снова на одной странице. Это было бы хорошей идеей, по крайней мере, для подключения к базе данных. Определите $ con только один раз в верхней части страницы и используйте его несколько раз. Просто потому, что вы закрываете свой php-тег (?>), Не означает, что вы потеряли переменные.

Для повторного использования кода я хотел бы взглянуть на определение функций для общих фрагментов кода. В идеале вы должны создавать классы для инкапсуляции логики. Например, типично иметь объект подключения к базе данных (или фреймворк), который инкапсулирует соединение, запрос и т. Д.

Возможно, вы можете взглянуть на Zend Framework. Это отличный инструмент для изучения PHP-разработчиков, чтобы увидеть отраслевые стандарты о том, как делать многие вещи, о которых вы просите.

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

+0

Тогда мой инструктор дал нам плохую информацию. Он сказал нам, что все, что вы делаете в php, существует только между рассматриваемыми открывающимися и закрывающимися тегами (переменные, функции, что угодно). Я всегда думал, что это кажется глупым, и это избавит меня от большого количества кода, который не имеет отношения к этому. – Elliot

+1

@Elliot Он, вероятно, имел в виду, что в HTML, пытаясь использовать '$ переменную', не входя в режим PHP, не приведет к завершению какой-либо операции. – Nightfirecat

+0

Кроме того, чтение о [variable scope] (http://php.net/manual/en/language.variables.scope.php) может помочь очистить понятия. –

-1

Есть несколько способов повторного использования кода в PHP. Самым простым и мощным является концепция functions.

Смежные вопросы