Change href link with php form

混江龙づ霸主 提交于 2019-12-10 14:22:50

问题


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. For example: Someone searches "Pinecones", if its in the database it'll have an ID, for this example its #4. Once they searched it, it'll show up as a link. But I want the link to use "/#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?


回答1:


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.




回答2:


I'm unclear what the problem is, for example I do not know whether you set $id and $output to any value. I don't know if the context of the code you posted is within a PHP string, or if it is in a template.

However if it is just a question of syntax then the following may be better:

As a PHP string:

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

An alternative:

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

In 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. Neither of these are functions, so it is proper to NOT include parenthesis like print('blah').



来源:https://stackoverflow.com/questions/30010135/change-href-link-with-php-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!