Post/Insert javascript variables to mySQL database table - presumably with ajax &/or jquery - How?
I'm posting my form below. Variable "e" in the form below is supposed to be the contents of a table cell on the same page. The part below that is in a file called insert.php. How can I put var e in mysql?
There are already a lot of answers to this question on google (and this site) with code that doesn't specify what to replace, with what, at what spots in the code, and what files which codes go in. Help us newbies with specifics! The code below seems to be a standard, how would myself and others modify this code to work with a variable? Var e being the contents of a table cell 开发者_开发技巧on the same page.
Thanks!
var e = document.getElementById("ItemName1").innerHTML);
<form action="insert.php" method="post">
<input type="hidden" name="save_name" value=e>
<input type=image
onmouseover='this.src="http://www.mysite.com/images/MouseOver.png"'
onmouseout='this.src="http://www.mysite.com/images/MouseOut.png"'
src="http://www.mysite.com/images/MouseOut.png">
</form>
<html>
<head>
</head>
<body>
<?php
$con = mysql_connect("localhost","removed for now","removed for now");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("removed for now", $con);
$sql="INSERT INTO Temp_Name (item_name) VALUES ('$_POST[save_name]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
echo $sql;
mysql_close($con)
?>
</body>
</html>
Change this line
$sql="INSERT INTO Temp_Name (item_name) VALUES ('$_POST[save_name]')";
to
$name = mysql_real_escape_string($_POST['save_name']);
$sql="INSERT INTO Temp_Name (item_name) VALUES ('$name')";
And read more about SQL Injection
and in a real scenario please don't echo your query string
To get the value of the input using javascript here is what you do
<input type="hidden" name="save_name" id="input1" value="e">
javascript:
var value = document.getElementById("input1").value;
First off, your Javascript has an unmatched closing brace, which I have to assume is accidental. Corrected version:
var e = document.getElementById("ItemName1").innerHTML;
To set the contents of this variable as the value of the hidden text field, you should (on pageload) do something like:
document.getElementById("hiddenelement").value=e;
and then change your form's hidden element to:
<input type="hidden" name="save_name" id="hiddenelement">
As for your mySQL query, what you have right now is extremely dangerous. You're executing an unescaped query that contains text that came from the client-side.
Please read about the vulnerability known as SQL injection
精彩评论