在 PHP 中回显变量的最佳方式

Best way to echo variable in PHP

根据我的阅读,不可能在回显中回显更多 PHP 代码,因此我正在寻找以下解决方案:

基本上,如果我的数据库中的 'closed_state' 列等于 'yes',则在末尾显示带有变量的 link 否则显示带有变量的不同 link最后。

这是我的代码:

<?php 

$result1    = mysqli_query($con,"SELECT closed_state FROM tbl_company WHERE company_id='$company_id'") or die(mysql_error());
$result2    = mysqli_query($con,"SELECT company_id FROM tbl_company WHERE company_id='$company_id'") or die(mysql_error());
$result3    = mysqli_query($con,"SELECT company_id FROM tbl_company WHERE company_id='$company_id'") or die(mysql_error());

while($row = mysqli_fetch_array($result1))
{
    if ($row['closed_state'] == "yes")
    {
        echo "<a href="customers_open.php?company_id=<?php while($row = mysqli_fetch_array($result2)) echo "{$row['company_id']}"; ?>">Reopen account</a>";
    } else {  
        echo "<a href="customers_close.php?company_id=<?php while($row = mysqli_fetch_array($result3)) echo "{$row['company_id']}"; ?>">Close account</a>";
    }
}   

?>

显然这行不通,那么实现这一目标的最佳方法是什么?

PHP 不可递归嵌入或执行。您不能在 php 字符串中嵌入 php 代码并让它自动执行,例如

<?php

$foo = "This is a <?php echo 'string'; ?> in PHP";
echo $foo;

将为您提供文字输出:

This is a <?php echo 'string'; ?> in PHP

而不是

This is a string in PHP

你想要的。

如果你想 "embed" php 那样,只需构建一个字符串:

 $foo = "This is a " . 'string' . " in PHP";

您没有正确引用您的字符串。如果你有字符串 echo "foo"bar" 那么中间的双引号将导致 PHP 结束字符串并尝试将 bar 解析为其他内容。

同样,您不能将 PHP 嵌套在 PHP 中。

    echo '<a href=....<?php while($row...

我认为您不需要 3 个查询。选择这两个值应该很好。无论如何,查询 2 和 3 是相同的。

$result1    = mysqli_query($con,"SELECT company_id, closed_state FROM tbl_company WHERE company_id='$company_id'") or die(mysql_error());
while($row = mysqli_fetch_array($result1)){
    if ($row['closed_state'] == "yes"){
        echo '<a href="customers_open.php?company_id='.$row['company_id'].'">Reopen account</a>';
    }else{  
        echo '<a href="customers_close.php?company_id='.$row['company_id'].'">Close account</a>';
    }
}   

我假设你的第二个和第三个查询实际上是不同的,否则没有重复的意义 - 但这是一个工作版本。

<?php 

$result1    = mysqli_query($con,"SELECT closed_state FROM tbl_company WHERE company_id='$company_id'") or die(mysql_error());
$result2    = mysqli_query($con,"SELECT company_id FROM tbl_company WHERE company_id='$company_id'") or die(mysql_error());
$result3    = mysqli_query($con,"SELECT company_id FROM tbl_company WHERE company_id='$company_id'") or die(mysql_error());

while($row = mysqli_fetch_array($result1))
{
    if ($row['closed_state'] == "yes")
    {
        $company_id = null;
        while($row = mysqli_fetch_array($result2)) $company_id = $row['company_id'];
        echo "<a href='customers_open.php?company_id={$company_id}'>Reopen account</a>";
    } else {
        $company_id = null;
        while($row = mysqli_fetch_array($result3)) $company_id = $row['company_id'];
        echo "<a href='customers_close.php?company_id={$company_id}'>Close account</a>";
    }
}   

?>