I'm very new to PHP & MySQL databases and was wondering how to create a random hyperlink in the text content pulled from the database.
It's a blog type website and I would like to make certain words in the paragraph refer to different websites: is that possible?
I know I can do something like this:
<?php
$sql = mysql_query("SELECT * FROM testblog ORDER BY id DESC");
while($row = mysql_fetch_assoc($sql)) {
$content = $row['content'];
$href = $row['href'];
?>
<p> <a href="<?php echo $href; ?>"> <?php echo $content; ?> </a> </p>
The issue with the above format is that the whole paragraph is a hyperlink whereas I prefer individual words and sometimes I may not even need to refer to a website.
Any help or simply pointing me in the right direct will be greatly appreciated, thanks!
I think what you are looking for is not PHP and is actually a Javascript thing.
You need to target specific words in the page body and replace them with a link. You can use the JKavascript replace function.
$("#myDiv").html().replace(/facebook/g, '<a href="http://www.facebook.com">Facebook</a>');
Then just repeat this for all of the links you want to add. The g
means that it will selector all links in the div id="myDiv"
If you wanted to do this for a random word you could make an array of words in php and then choose one using rand()
and then echo that into various parts of the Javascript. Example to follow
PHP
$word = array('facebook', 'twitter', 'john', 'mary'); // array of words
$i = rand(0, count($word)-1); // generate random number size of the array
$randword = "$word[$i]"; // set variable equal to which random word was chosen */
JavaScript
$("#myDiv").html().replace(/<?php echo $ranword; ?>/g, '<a href="http://www.thiswebsite.com"><?php echo $ranword; ?></a>');
Or something like this.