PHP bir sayfada kalıcı değişkenler

2 Cevap php

Ben üzerinde çalışıyorum bir sayfada, böyle dinamik Javascript işlemek için baş bir ve tablo oluşturulması için ana gövdedeki biri olarak PHP birkaç farklı parça var. Bununla birlikte, operasyon, SQL sorgularını vb birçok iki alan arasındaki aynıdır. Örneğin, ben tekrar aynı veritabanına yeniden zorunda tutmak. Seni çok çoğaltılması ve tekrarlanan hesaplama olması gerekmez ki bana kodlarını düzene için bazı yolu var mı?

Sayfa kod, bu ek dosyalar olmadan doğru görünmüyor rağmen. Ayrıca, çok uzun.

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

Sen tek bir sayfada ve üzerinde değişkenleri yeniden kullanabilirsiniz. Bu, en azından veritabanı bağlantısı için bir iyi bir fikir olacaktır. Sayfanın üst kısmında sadece bir kez $ con tanımlamak ve bunu birden çok kez kullanın. Eğer php tag (>) kapatmak sırf size değişkenleri kayıp anlamına gelmez.

Yeniden kullanım kod için, ben ortak kod parçaları fonksiyonlarını tanımlayan bir göz alacaktı. İdeali, mantığını saklanması sınıfları oluşturmak olacaktır. Örneğin, bağlantı, sorgulama, vb kapsüller hangi bir veritabanı bağlantı nesnesi (veya çerçeve) olması normaldir

Sen Zend Framework bir göz alarak yararlanabilir. Bu soruyor pek çok şeyi nasıl endüstri standartlarını görmek için PHP geliştiriciler öğrenmek için harika bir araçtır.

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

Php kodu yeniden için çeşitli yollar vardır. En temel ve güçlü bir functions kavramdır.