简体   繁体   English

用php表单更改href链接

[英]Change href link with php form

I'm making a website with a search bar. 我正在建立一个带搜索栏的网站。 I want to make the search bar interactive once it has "searched" and shown the results. 我希望搜索栏在“搜索”并显示结果后进行交互。 So I want the href to chnage as per what Id is being used. 所以我希望href能够根据Id的使用情况进行控制。 For example: Someone searches "Pinecones", if its in the database it'll have an ID, for this example its #4. 例如:有人搜索“Pinecones”,如果它在数据库中它有一个ID,对于这个例子它是#4。 Once they searched it, it'll show up as a link. 一旦他们搜索了它,它就会显示为一个链接。 But I want the link to use "/#IDNumber.php" 但我希望链接使用“/#IDNumber.php”

This is the code im using: 这是我正在使用的代码:

<?php
$output = '';
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);

$query = mysql_query("SELECT * FROM `findgame` WHERE name LIKE '%$searchq%'       OR keywords LIKE '%$searchq%' LIMIT 1") or die("Search unavailable.");
$count = mysql_num_rows($query);
if($count == 0){
    $output = 'Results not found.';

}else{
    while($row = mysql_fetch_array($query)) {
        $name = $row['name'];
        $kwords = $row['keywords'];
        $id = $row['id'];

        $output .= '<div style="position:absolute;margin:110px    20px;padding:25px;">'.$id.' '.$name.'</div>';
        }

}

}

?>

and

<a href="/<?php$id?>.php">    <?php print("$output");?></a>

Any help in making it work? 有什么帮助使其工作?

You need to print the variable. 您需要打印变量。

$id = 123;

<?php $id ?>      =>
<?php echo $id ?> => 123
<?= $id ?>        => 123

So the final result would be something like: 所以最终的结果是这样的:

<a href="/<?= $id ?>.php">
    <?php print($output); ?>
</a>

Note: You don't need the " around $output . It won't hurt, but it's not necessary. 注意:你不需要"大约$output 。它不会受到伤害,但没有必要。

I'm unclear what the problem is, for example I do not know whether you set $id and $output to any value. 我不清楚问题是什么,例如我不知道你是否将$ id和$ output设置为任何值。 I don't know if the context of the code you posted is within a PHP string, or if it is in a template. 我不知道您发布的代码的上下文是否在PHP字符串中,或​​者它是否在模板中。

However if it is just a question of syntax then the following may be better: 但是,如果它只是一个语法问题,那么以下可能会更好:

As a PHP string: 作为PHP字符串:

$out = '<a href="/' . $id . '">' . $output . '</a>';

An alternative: 替代:

$out = "<a href=\"/$id.php\">$output</a>";

In HTML: 在HTML中:

<a href="/<?php print $id; ?>.php"><?php print $output; ?></a>

or even: 甚至:

<?php print '<a href="/' . $id . '">' . $output . '</a>'; ?>

I hope that is all your problem was. 我希望你的问题都是。

Note print and echo can be used interchangeably, people prefer print in this scenario although echo is slightly faster IIRC. 注意打印和回声可以互换使用,人们更喜欢在这种情况下打印,尽管回声稍快一些IIRC。 Neither of these are functions, so it is proper to NOT include parenthesis like print('blah'). 这些都不是函数,所以不包括像print('blah')这样的括号是合适的。

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

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