Conor Holman
Conor Holman

Reputation: 31

Add link to my PHP echo

So I have a PHP script that fetches the 'names' of some ID's on my DB. It then displays these 'names' on my index page as a user begins to search in the search bar. What I just can't seem to get working is the href link. I wish the 'names' that appear, hyperlink to their given page. Example: I search for The Beatles in the search bar 'The Beatles' is displayed on my search result and when I click 'The Beatles' link it takes me to www.mywebsite.com/'thebeatles'.html and it gives me thebealtes.html based on the 'names' that was fetched by my PHP script.

$host = "localhost";
$user = "root";
$password = "";
$db = "images";

$conn=mysqli_connect($host, $user, $password, $db);

if(!empty($_GET['q'])){

    $q = $_GET['q'];
    $query = "SELECT * FROM names WHERE names like '%$q%'";
    $result = mysqli_query($conn, $query);
    while($row = mysqli_fetch_assoc($result)){

        $name = $row['names'];

        echo '<a href=..........><div class="searchoutput">'.$name.'</a><br><div class="col-md-8"></div></div>';

    }
}

If someone could help me figure out what I put where I have put href=........ that would be great.

Upvotes: 0

Views: 141

Answers (2)

kscherrer
kscherrer

Reputation: 5766

Althought there are some good answers, they all have some mistakes that they overlooked.

  1. href attribute needs quotes

  2. When you open a div inside an a-tag, you need to close the div before closing the a-tag

    $host = "localhost";
    $user = "root";
    $password = "";
    $db = "images";
    
    $conn=mysqli_connect($host, $user, $password, $db);
    
    if(!empty($_GET['q'])){
    
    $q = $_GET['q'];
    $query = "SELECT * FROM names WHERE names like '%$q%'";
    $result = mysqli_query($conn, $query);
    while($row = mysqli_fetch_assoc($result)){
    
        $name = $row['names'];
        $href = str_replace(' ', '', strtolower($name));
    
        echo '<a href="'.$href.'.html"><div class="searchoutput">'.$name.'</div></a><br><div class="col-md-8"></div>';
    
        }
    }
    

Upvotes: 1

thiello_7
thiello_7

Reputation: 16

$link = str_replace(' ', '', strtolower($name));
echo '<a href="'.$link.'html"><div class="searchoutput">'.$name.'</a><br><div class="col-md-8"></div></div>';

Upvotes: 0

Related Questions