Reputation:
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?
Upvotes: 5
Views: 2932
Reputation: 1600
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').
Upvotes: 0
Reputation: 3059
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.
Upvotes: 4