[FIXED] Can I prevent running javascript as input on my php website using mysqli_prepare()

Issue

I am using mysql_prepare() function to avoid SQL injection on my website. and I was wondered that if it is working!!

when I use <script>alert("something")</script> as an input of one of the fields, the script goes to my database, and I was wondered if it is normal !?!

Am I missing something?

or the prepare function just avoid SQL injection.


Solution

No, you can't prevent the execution of JavaScript on your page by using parameterized queries.

The whole purpose of using parameterized queries is to prevent your SQL from breaking when an unexpected input is provided. When you bind the data separately from the SQL then there is no way that the data could affect the SQL. For example:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'test');
$mysqli->set_charset('utf8mb4'); // always set the charset

$email = '1 or 1=1';
$stmt = $mysqli->prepare('SELECT user FROM users WHERE email=?');
$stmt->bind_param('s', $email);
$stmt->execute();

In this example, the email looks like SQL, but it will never be treated as SQL by MySQL server. It is bound separately so MySQL receives it already after parsing the SQL. This helps to prevent SQL injection. Never escape the data that you bind!

As you can see prepared statements only protect SQL. They don't protect users from submitting JavaScript or HTML code into your database. You would need to add extra validation rules or simply treat it as any other data.

To prevent JavaScript or HTML or any other data from breaking your site, you need to make sure that you always follow the best practices when it comes to output. You must always format the data correctly.



Answered By - Dharman
Answer Checked By - Katrina (sql.easybugfix Volunteer)

Related Posts

Post a Comment