u19981010
u19981010

Reputation: 15

Get html link from database with PHP

I have a database table that contains these rows, "id" ,"link" and "name" with link being :

<a href=\"https://www.sample.com/file1.php\">[1-200]< /a> <a href=\"https://www.sample.com/file2.php\">[201-224]< /a>

and name :

item1

I have the following PHP code to get the info from the database and return it to visitors. My problem is that the link for file2.php, is not only applied as hyper link for [201-224], the hyperlink is applied for the rest of the page content also. How do I prevent this? And thanks in advance.

echo "</br> ".$name=  $row['name'];
        echo "</br> ".$Torrentlink= preg_replace('/\\\\/', '',$row['Torrentlink']);

        echo "</br> ";
        echo "</br> ";echo "</br> ";
        echo "the rest of my text goes here ";

Upvotes: 0

Views: 1337

Answers (3)

Daniel Gale
Daniel Gale

Reputation: 663

This is a terrible way to handle this type of data. If you know they are all links then you should only be storing the link and the name (of course id and other meta data could be useful). Your current situation allows for too many errors and a maintenance problem for those working behind you. If you do not want to create a record for each link, consider storing them as JSON or some other format.

Example: (Store JSON in DB as VARCHAR)

<?php

//Populate variable from DB
//$TorrentLinks = $row{'Torrentlink'};
$TorrentLinks = '[
     {"url":"https://www.sample.com/file1.php","text":"[1-200]"},
     {"url":"https://www.sample.com/file2.php","text":"[201-224]"}
]';

//Convert to array
$jsonLinks = json_decode($TorrentLinks,true);

//Iterate and print links
foreach ($jsonLinks as $key => $value) {
    echo "<a href=\"{$value["url"]}\">{$value["text"]}</a><br />";
}

Results:

<a href="https://www.sample.com/file1.php">[1-200]</a>
<a href="https://www.sample.com/file2.php">[201-224]</a>

Depending on how you capture the data, you could also use something like htmlspecialchars() to keep the special characters from executing.

Upvotes: 1

u19981010
u19981010

Reputation: 15

the error was simply the input html text.

the problem was the " < /a> " in the line:

<a href=\"https://www.sample.com/file1.php\">[1-200]< /a> <a href=\"https://www.sample.com/file2.php\">[201-224]< /a>

I had a space before the the backslash.

Upvotes: 0

AIPohja
AIPohja

Reputation: 1

I think there's a problem with your preg_replace('/\\\\/', '',$row['Torrentlink']);

/\\\\/ finds text with double backslash \\. It seems that your intention is to find only single backslashes to get rid of them in your links.

So try replacing it with

preg_replace('/\\/', '',$row['Torrentlink']);

For example https://regexr.com/ is a good place to check your regular expressions.

Upvotes: 0

Related Questions