0

我最近学会了通过 php 创建动态链接,但我今天的问题是我不知道如何在 php 块中执行此操作,例如我知道如何执行此操作:

     <div><a href="blah.php?id=<?php echo $id; ?>">content</a></div>

但是我在 php 块中的 head 标签上方执行此操作,所以基本上我正在为动态内容创建一个动态链接,本质上我将在主页上动态呈现图像,这些图像是指向产品的链接。这就是我所拥有的:

    <?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>";
          }
   ?>

这可能真的很容易,但我找不到它,也许我没有问魔法谷歌正确的问题。提前致谢!

4

3 回答 3

3

逃避问题,改变:

 $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>";

至:

 $dynamic_newest .= "<a href=\"blah.php?id=$id\"><img src='inventory_images/$pid.jpg' width='100px' height='100px' /></a>";
于 2012-06-25T20:09:08.857 回答
2

不确定这是否是您正在寻找的,但无论如何..

$dynamic_newest .= "<a href='blah.php?id=$pid'><img src='inventory_images/$pid.jpg' width='100px' height='100px' /></a>";
于 2012-06-25T20:11:10.383 回答
2

虽然您现在不使用它,但我相信您将来会发现它的用途。稍后,当您需要编写大块预格式化的非 php 文本并希望在其中添加 php 变量时,可以执行以下操作:

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 个月后调试更容易。

于 2012-06-25T20:18:46.440 回答