views:

225

answers:

2

On a page I am working on, I have several distinct pieces of PHP, such as one in the head to handle dynamic Javascript and one in the main body for table creation. However, many of the operations, SQL queries, etc. are the same between the two area. For example, I keep having to reconnect to the same database over and over. Is there some way for me to streamline the code so that I do not need to have so much duplication and repeated calculation?

The page code, although it won't look right without the supplementary files. Also, it's very long.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;

<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  A: 

You can re-use variables over and over on a single page. This would be a good idea for at least the database connection. Define $con just once at the top of the page and use it multiple times. Just because you close your php tag (?>) doesnt mean you lost your variables.

For code re-use, I would take a look at defining functions for common code fragments. Ideally, you would create classes to encapsulate logic. For example, it is typical to have a database connection object (or framework) which encapsulates connecting, querying, etc.

You may benefit from taking a look at the Zend Framework. It is a great tool for learning PHP developers to see industry standards on how to do many of things you are asking.

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

Brad
My instructor gave us bad info, then. He told us that anything you do in php exists only between the opening and closing tags in question (variables, functions, whatever). I always thought that seemed dumb, and it will save me a lot of code not dealing with that.
Elliot
A: 

There are several ways to reuse code in php. The most basic and powerful one is the concept of functions.

troelskn