Home  >  Article  >  Backend Development  >  为何有时候要将一段完整的php代码分开写呢

为何有时候要将一段完整的php代码分开写呢

WBOY
WBOYOriginal
2016-06-13 12:00:39918browse

为什么有时候要将一段完整的php代码分开写呢?

本帖最后由 u014060468 于 2014-06-20 09:53:43 编辑 见代码,我不明白为什么要将一段完整的php代码分开写?如果我合在一起写会怎样嘛?
include("Conn/conn.php");
$query=mysql_query("select book.barcode,book.id as bookid,book.bookname,bt.typename,pb.pubname,bc.name from tb_bookinfo book join tb_booktype bt on book.typeid=bt.id join tb_publishing pb on book.ISBN=pb.ISBN join tb_bookcase bc on book.bookcase=bc.id");
$result=mysql_fetch_array($query);
        if($result==false){
?>
 
          
            
              
            
          
暂无图书信息!

          
  
    
  

      添加图书信息 

 }else{
?>

------解决方案--------------------
黑色部分的部分是 html 代码,不是 php 代码
你可以说是 php 中嵌入了 html,也可以说是 html 中嵌入了 php
这种书写方式的优点是可以用可视化 html 工具(比如 DW)观察和修改 html 部分

合在一起的话,html 部分就要放在字符串中。由于同时存在单双引号,转义使可视性下降
如果是用自定义定界符,由于规则所在,代码的美观度下降
你也可以放在单独文件里,include 进来。不过离开了视觉空间,会影响思维的连续性
------解决方案--------------------
首先php是在服務器解釋的,而html是在瀏覽器解釋。php會比html先運行。


因為中間不是php代碼,所以要分開兩個php塊來寫
如果你需要合起來一整段都是php,中間的html你要改用php 的echo來寫。

例如

<br /><?php<br />include("Conn/conn.php");<br />$query=mysql_query("select book.barcode,book.id as bookid,book.bookname,bt.typename,pb.pubname,bc.name from tb_bookinfo book join tb_booktype bt on book.typeid=bt.id join tb_publishing pb on book.ISBN=pb.ISBN join tb_bookcase bc on book.bookcase=bc.id");<br />$result=mysql_fetch_array($query);<br />if($result==false){<br />  echo '<table width="100%" height="30"  border="0" cellpadding="0" cellspacing="0">';<br />  echo '<tr>';<br />  echo '<td height="36" align="center">暂无图书信息!</td>';<br />  echo '</tr>';<br />  echo '</table>';<br />  echo '<table width="100%"  border="0" cellspacing="0" cellpadding="0">';<br />  echo '<tr>';<br />  echo '<td>';<br />  echo '<a href="book_add.php">添加图书信息</a> </td>';<br />  echo '</tr>';<br />  echo '</table>';<br />}else{<br /><br />}<br />?><br />

------解决方案--------------------
html+php混编模式

通过模板smarty可以将php和html分离,方便维护。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn