Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

punchi's avatar

"Correct" way to echo from DB

PHP 7, working with UTF-8

$model = new Model();
$model->text = "This quo'<script>alert('omg')</script>";
$model->save();

Good!

In DB, the field is:

This quo'<script>alert('omg')</script>

Good!

On a view

{{$model->text}}

And says:

This quo'<script>alert('omg')</script>

Good!

But when working with AJAX and returning the string from database, doing the "echo", appears the "omg" alert on browser. So, my question is, which is the best way to handle this?

  1. Write the escaped character on the DB? (dont like that)
  2. Put a htmlspecialchars() on all the string?
  3. Make an extra effort to, instead return the string directly, pass to a view and return the string from the view
  4. Other? =)

I know there's no "best" but right now I have escaped the string with htmlspecialchars(), any other more productive or "laravel" way to do this?

0 likes
2 replies
punchi's avatar

Thank you!! yep,

htmlentities($value, ENT_QUOTES, 'UTF-8', false);

Was my solution =)

Please or to participate in this conversation.