繁体   English   中英

PHP url变量传递会打印变量名而不是值

[英]PHP url variable passing prints variable name not the value

我正在尝试通过URL传递字符串,以通过另一个php页面中的echo语句进行打印,但是它将打印变量名称而不是值

第1页:

<p><?php $first = $row['post'];
    $string = substr($row['post'], 0, 200);
    echo $string;
    ?></p>

    </header>
    <a href="#" class="image main"><img src="images/pic01.jpg" alt="" /></a>
    <ul class="actions special">
    <a href="article.php?posters='.$first.'" class="button large">
        Full Story</a>

这是我试图将变量的值首先通过url传递到下一页的代码

第2页:

<p><?php echo $_GET['posters'];?></p>

这就是我在第2页中所说的,结果打印在该页上是

'.$first.'

如何获取它以打印变量$first而不是名称的实际值。

简单修复:

<a href="article.php?posters=<?php echo $first ?>" class="button large">Full Story</a>  

希望这可以帮助!

由于OP没有提到$row['post']的值,因此我随意地选择了一个并操纵了它,然后将其分配给$first ,如下所示:

<p><?php 
$row['post'] = "The rain in Spain stays mainly in the plain";
$first = substr($row['post'], -5, 5);
?></p>
</header>
<a href="#" class="image main"><img src="images/pic01.jpg" alt="" /></a>
<ul class="actions special">
<a href="article.php?posters=<?=urlencode($first) ?>" class="button large">
    Full Story</a>

查看实时代码

标签是HTML,不属性任何特殊含义的点,不像PHP它认为它作为连接运算符,所以你应该删除这两个点。

为了在将PHP嵌入HTML中时显示变量的PHP值(目前不是最佳实践;请参见MVC ),有两种方法。 一种是使用echo,但也有一个可行的速记,本示例也使用速记,即<?=$first

注意:构造url时,好的做法是使用urlencode() 另外,您不需要在网址的查询字符串部分中使用单引号; 单引号可防止对变量值进行字符串插值,因此您看到的是文字变量名称。

<?php 

//single quoutes return variable name

$first = "hello";
echo '$first'; //$first

//double quoutes return variable value
$first = "hello";
echo "$first" ;  // hello

?>   

因此,在第1页中,您必须使用双引号

<a href="article.php?posters=<?php echo $first ?>" class="button large"> Full Story</a>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM