首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP代码块中的php动态链接

问PHP代码块中的php动态链接
EN

Stack Overflow用户
提问于 2012-06-26 04:07:44
回答 3查看 1.7K关注 0票数 0

我最近学会了通过php创建动态链接,但我今天的问题是我不知道如何在php代码块中做到这一点,例如我知道如何做到这一点:

代码语言:javascript
复制
     <div><a href="blah.php?id=<?php echo $id; ?>">content</a></div>

但我是在php代码块的head标签上做这个的,所以基本上我是在为动态内容创建一个动态链接,基本上我要在主页上动态呈现图像,这些图像是指向产品的链接。这就是我所拥有的:

代码语言:javascript
复制
    <?php 
     include_once "scripts/connect_to_mysql.php";
     //Select query for latest items
     $dynamic_newest = "";
     $sql = mysql_query("SELECT * FROM products ORDER BY date_added DESC LIMIT 24");
     $productCount = mysql_num_rows($sql); // count the output amount
     if ($productCount > 0) {
          while($row = mysql_fetch_array($sql)){
              $id = $row["id"];
              $pid = $id;
              $category = $row["category"];
              $subcategory = $row["subcategory"];
              $dynamic_newest .= "<a href="THIS IS WHAT I DONT KNOW HOW TO DO"><img src='inventory_images/$pid.jpg' width='100px' height='100px' /></a>";
        }
          } else {
          $dynamic_newest = "<h1>There are no products to display yet.</h1>";
          }
   ?>

这可能真的很简单,但我找不到它,也许我没有问到magic google正确的问题。提前感谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-06-26 04:11:10

我不确定这是否是你要找的,但不管怎样..

代码语言:javascript
复制
$dynamic_newest .= "<a href='blah.php?id=$pid'><img src='inventory_images/$pid.jpg' width='100px' height='100px' /></a>";
票数 2
EN

Stack Overflow用户

发布于 2012-06-26 04:09:09

逃避问题,改变:

代码语言:javascript
复制
 $dynamic_newest .= "<a href="THIS IS WHAT I DON'T KNOW HOW TO DO"><img src='inventory_images/$pid.jpg' width='100px' height='100px' /></a>";

至:

代码语言:javascript
复制
 $dynamic_newest .= "<a href=\"blah.php?id=$id\"><img src='inventory_images/$pid.jpg' width='100px' height='100px' /></a>";
票数 3
EN

Stack Overflow用户

发布于 2012-06-26 04:18:46

虽然您现在不使用它,但我相信您将来会发现它的用处。稍后,当您需要编写大量预格式化的非php文本块并想要向其中添加php变量时,您可以这样做:

代码语言:javascript
复制
echo<<<YOUR_IDENTIFIER

<h1>Hi!</h1>
<form action='post'>
Welcome to my webpage =).
You can place code here as if it were not inside a PHP block,
but you can also use PHP variables. That means you can even
insert quotes like this --> "", though since this is still HTML,
it would be more accurate to use &gt; and &quot;. Your cleanest
bet and best-practice coding method is to {$encapsulate} php
variables in squiggley brackets. You can even
{$encapsulateArrays['likethis']}.
</form>

YOUR_IDENTIFIER;

echo "Back to regular PHP code.";

确保YOUR_IDENTIFIER;前没有空格或制表符。

要回答你最初的问题(与我上面的长篇大论无关),请确保正确地使用反斜杠\任何引号进行转义,以免意外终止字符串文字。别忘了用{}封装你的变量,即使你在做常规的echo "My {$variable} here";,它也不会影响解析,但当你在做下一个项目时,2个月后的调试会变得容易得多。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11196568

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档