Store HTML into MySQL database

夙愿已清 提交于 2019-11-29 05:23:21

Strings in a SQL query are -usually- surrounded by singlequotes. E.g.

INSERT INTO tbl (html) VALUES ('html');

But if the HTML string itself contains a singlequote as well, it would break the SQL query:

INSERT INTO tbl (html) VALUES ('<form onsubmit="validate('foo', 'bar')">');

You already see it in the syntax highlighter, the SQL value ends right before foo and the SQL interpreter can't understand what comes thereafter. SQL Syntax Error!

But that's not the only, it also puts the doors wide open for SQL injections (examples here).

You'll really need to sanitize the SQL during constructing the SQL query. How to do it depends on the programming language you're using to execute the SQL. If it is for example PHP, you'll need mysql_real_escape_string():

$sql = "INSERT INTO tbl (html) VALUES ('" . mysql_real_escape_string($html) . "')";

An alternative in PHP is using prepared statements, it will handle SQL escaping for you.

If you're using Java (JDBC), then you need PreparedStatement:

String sql = "INSERT INTO tbl (html) VALUES (?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, html);

Update: it turns out that you're actually using Java. You'll need to change the code as follows:

String sql = "INSERT INTO website (URL, phishing, source_code, active) VALUES (?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, URL);
preparedStatement.setString(2, phishingState);
preparedStatement.setString(3, sourceCode);
preparedStatement.setString(4, webSiteState);
preparedStatement.executeUpdate();

Don't forget to handle JDBC resources properly. You may find this article useful to get some insights how to do basic JDBC stuff the proper way. Hope this helps.

Try using mysql_real_escape_string function on the string you want to store. It is the easiest way.

You need to escape a string before inserting it into database.

Difficult to say without seeing the query. Can you post it?

I'm presuming there's some part of the html string that needs escaping, which maybe you missed?

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