0

So i am making a very basic site where someone types in a box some text and it posts it into mysql.

Example:

Here is my post with a cool link - htt://www.coolness.com

The following script simply grabs the column wanted from the database and echos it on a line.

<?php
$con = mysql_connect("localhost","####","####");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("####", $con);

$result = mysql_query("SELECT * FROM posts");

while($row = mysql_fetch_array($result))
  {
  echo $row['post_content'];
  echo "<br />";
  }

mysql_close($con);
?>

The link is in plain text and instead I would like either php or javascript to write it as a hyperlink by adding the whole bit to it.

I've looked through examples, but nothing seemed to work when I tried to apply them.

Any tips would be great.

2

2 Answers 2

1

Hope I understood what you meant:

Change to

while($row = mysql_fetch_array($result))
  {
  echo '<a href="' . $row['post_content'] . '">' . $row['post_content'] . '</a>';
  echo "<br />";
  }

What this code does, is that it prints the links inside <a> tags, which are links.

Sign up to request clarification or add additional context in comments.

2 Comments

Correct, but not everything they post into the database will be a link. This would just make the whole post in mysql a link. Here is my post with a cool link - urladdress into Here is my post with a cool link - <a href="urladdress">urladdress</a>
Okey, now I think I understand what you meant. You could use a regular expression (regex) to find URLs in the text, and then surround those with the <a href=""> stuff.
1

Use preg_replace() in PHP. Pass it a regular expression for a URL, how you want that matched URL to be replaced, and then the string you pulled from your DB.

You want to turn "http://www.coolness.com" into "http://www.coolness.com'>http://www.coolness.com".

See this question for discussion on regexes for URL matching, and this piece of the PHP documentation for more on the preg_replace() function.

EDIT: SO seems to have had fun with my second line there! It should read:

You want to turn "http://www.coolness.com" into "<a href='http://www.coolness.com'>http://www.coolness.com</a>".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.