簡體   English   中英

如何將帶引號的字符串正確保存到數據庫以進一步顯示?

[英]How to properly save string with quotation marks to database for further displaying?

我想在數據庫上保存一些表單數據。 表格:

echo '<form action="post" method="'.$_SERVER['PHP_SELF'].'">
<input type="text" name="first_name" value="htmlspecialchars($_POST['first_name']).' />
<input type="text" name="last_name" value="htmlspecialchars($_POST['last_name']).' />
<input type="submit" name="submit" />
</form>';

如果某些輸入為空,則會刷新到同一頁面,並在頂部顯示錯誤,以說填滿了輸入。

問題是,當我僅填充一個輸入以值aaa” aaa,而另一輸入保存為空時,則比我提交的多。然后我得到了錯誤,說要填充另一輸入並且填充值從aaa” aaa變為aaa” aaa。

因此,當我將數據保存到數據庫中時,某些數據會被轉義,而某些數據則不會。

我以為使用htmlspecialchars_decode,但是如果我要鍵入aaa”“ aaa”,則當我希望將其原樣保存時將其轉換為“ aaa”“ aaa”(aaa” aaa)。

我可以做什么?

謝謝!

好吧,我建議您使用Javascript驗證來檢查每個字段,然后如果一切正常,則將其保存在數據庫中。

如果您需要驗證用戶數據,則肯定需要在前端(javascript)和后端(出於安全原因)進行驗證。

無論如何,首先我在您的php代碼中看到錯誤。 沒有適當的串聯符號和引號。 正確的代碼段應為:

echo '<form action="post" method="'.$_SERVER['PHP_SELF'].'">
<input type="text" name="first_name" value="'.htmlspecialchars($_POST['first_name']).'" />
<input type="text" name="last_name" value="'.htmlspecialchars($_POST['last_name']).'" />
<input type="submit" name="submit" />
</form>';

如果您確實要顯示由用戶插入的配額標記,則可以使用html_entity_decode($your_variable_here);

$orig = "I'll \"walk\" the <b>dog</b> now";
$a = htmlspecialchars($orig);
$b = html_entity_decode($a);
echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now
echo $b; // I'll "walk" the <b>dog</b> now

更多信息在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM