How to insert a php code snippet in mysql database

断了今生、忘了曾经 提交于 2019-11-29 18:16:43

Yeah, you can do this. Multiple ways:

  1. PDO - that's the best option actually. Study this topic in the PHP manual as this can be a lot more help than just protecting your MySQL queries in PHP from breaking.
  2. addslashes() - adds slashes to escape characters. This won't break your MySQL query for sure.
  3. mysql_real_escape_string()
  4. mysql_escape_string()

EDITED Emphasized PDO as compared to the previous version of this answer as PDO is far more safer than the other options and there is a lot more to it which can be used while working with PHP and MySQL.

Escape special characters using mysql_real_escape_string(). You'd probaply be better off moving away from mysql_* functions though and start using PDO or mysqli_* for example.

Edit As mentioned in the comments, make sure you place the code as a string and that the DB field is the correct data type. Also, make sure you use mysql_real_escape_string() (if you insist on using mysql_*) on the whole string (or code).

You will need to use mysql_real_escape_string() to escape the php code so it does not throw an error when inserting. Then you run an eval() on the statement, if you want it to execute. If you have a mixed html and php stored in the database you would call eval like so

 eval('?>'.$dbresult.'<?php');

Just make sure you stripslashes() on the database result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!