Is it unsecure to embed PHP code in a javascript function?
My friend told me not to do it.
My script just inserts a number in the database if the message has been clicked (read).
<!--Insert into database when click-->
<script>
function insert()
{
<?php
include 'db_connect.php';
$usermsg = $_SESSION['username'];
$message_id = $_GET['messageid'];
mysql_query("UPDATE messages SET message_read='1' WHERE id='$message_id' AND to_user='$usermsg'");
?>
}
</script>
Should i do this any otherway? Or drop including php & mysql in my script and start over?
If you try that code, it won’t even work that way. You cannot embed server side code in javascript function.
What you want is to make a sepearate request that will handle the request. This method is called AJAX. With jQuery library you can make AJAX POST request like this:
In test.php:
Read the Beginners Guide to Using AJAX with jQuery
And don’t forget to use parametrized sql to prevent sql injection attacks as this code in its current state is vulnurable.