2012-09-26 41 views
0

我從頭開始構建個人博客,並且在從MySQL輸出文本正文時讓我的鏈接正確顯示時遇到了問題。顯示來自MySQL數據庫的文本正文內的鏈接

例如; 當我從數據庫中調用博客文章的鏈接無法正確顯示時,我有一個鏈接將大約200字內嵌到博客文章中。我曾嘗試使用stipslashes()htmlentities(),這兩者都不起作用。

這裏是我的代碼的博客文章保存到數據庫:

function check_input($data, $problem='') 
{ 
$data = trim($data); 
$data = stripslashes($data); 
$data = htmlspecialchars($data); 
if ($problem && strlen($data) == 0) 
{ 
    die($problem); 
} 
    return $data; 
} 

if(isset($_POST['addBlog'])) { //form submitted? 

// get form values, escape them and apply the check_input function 
$title = $link->real_escape_string($_POST['title']); 
$category = $link->real_escape_string(check_input($_POST['category'], "You must choose a category.")); 
$content = $link->real_escape_string(check_input($_POST['blogContent'], "You can't publish a blog with no blog... dumbass.")); 
$date = $link->real_escape_string(check_input($_POST['pub_date'], "What day is it foo?")); 


mysqli_connect($db_host, $db_user, $db_pass) OR DIE (mysqli_error()); 
// select the db 
mysqli_select_db ($link, $db_name) OR DIE ("Unable to select db".mysqli_error($db_name)); 

// our sql query 
$sql = "INSERT INTO pub_blogs (title, date, category, content) VALUES ('$title', '$date', '$category', '$content');"; 

//save the blog  
mysqli_query($link, $sql) or die("Error in Query: " . mysqli_error($link)); 

if (!mysqli_error($link)) 
{ 
    print "<p> Blog Successfully Published! </p>"; 
} 
} 

這裏是我的代碼,以顯示博客文章:這是麻煩的是

  // Grab the data 
     $result = mysqli_query($link, "SELECT * FROM pub_blogs") or die ("Could not access DB: " . mysqli_error($link)); 
     while ($row = mysqli_fetch_assoc($result)) 
     { 
      $id = $link->real_escape_string($row['id']); 
      $title = $link->real_escape_string($row['title']); 
      $date = $link->real_escape_string($row['date']); 
      $category = $link->real_escape_string($row['category']); 
      $content = $link->real_escape_string($row['content']); 

      $id = stripslashes($id); 
      $title = stripslashes($title); 
      $date = stripslashes($date); 
      $category = stripslashes($category); 
      $content = stripslashes($content); 

     } 
     echo "<div class='blog_entry_container'>"; 
     echo "<span class='entry_date'><a href='#'>" .$date. "</a> - </span><span class='blog_title'><a class='blogTitleLink' href='#'>" .$title. "</a></span>"; 
     echo "<p>" .$content. "</p>"; 
     echo "</div>"; 

問題在於$content變量

+1

我認爲你需要addslashes而不是stripslashes –

+0

不,這只是增加了更多的斜線。我已經試過了。 –

+0

你能粘貼你到$內容? – GBD

回答

0

您應該切換到pr相互陳述,並擺脫所有逃脫和削減的東西。

這應該會在數據庫中正確地獲得原始博客文章,但現在您遇到了問題:您應該使用htmlspecialchars將內容輸出到html(以避免文本變成標籤等問題),但這會破壞您的鏈接。

解決這個問題的方法是使用標記語言(如markdown)將您的鏈接轉換爲html鏈接。另請參閱此blog post by Jeff Atwood關於SO的問題和答案的標記。

另一種方法是將內容完全寫入html並擺脫周圍的<p>標籤,但只有當您(或可信用戶)是唯一可以寫博客條目的人才能使用。或找到一個很好的方式來清理/驗證您的輸入當然...

+0

因此,如果我將查詢切換到準備好的語句並擺脫所有轉義和削減的東西,我的鏈接是否會正確顯示? –

+0

@Ty Bailey如果你的鏈接是html,是的,但是你可以通過在你的內容中使用諸如'<', '>'等字符來輕鬆地使你的html無效。 – jeroen

相關問題