为什么这个PHP脚本不会将表单数据提交给mysql?
This script is supposed to get the content of a text area and submit it to mysql, but it isnt can anyone see why?
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$error = '';
$like = mysql_real_escape_string($_POST['like_box']);
mysql_query("INSERT INTO likes (like) VALUES ($like)");
$id = mysql_query("SELECT id FROM likes WHERE like=$like");
header('Location:like.php?id='.$id.'');
}?>
<form method="post" action="post.php">
<textarea name="like_box" id="like_box" style="border-style: none; border-color: inherit; border-width: 0; width: 458px; height: 65px" class="style11120"></textarea>
<tr>
<td style="height: 53px">
<div class="style11116" style="width: 417px">
<input name="Submit" type="submit" value="submit" />
</form>
这个脚本应该获取文本区域的内容并将其提交给mysql,但它不是任何人都能看到的 为什么? p>
if($ _SERVER [“REQUEST_METHOD”] ==“POST”)
{
$ error ='';
$ like = mysql_real_escape_string($ _POST ['like_box']);
mysql_query(“INSERT INTO like(like)VALUES($ like)”);
$ id = mysql_query(“SELECT id FROM like WHERE like = $ like”);
header('Location:like.php?id ='。$ id。'');
}?&gt;
&lt; form method =“post”action =“post.php”&gt ;
&lt; textarea name =“like_box”id =“like_box”style =“border-style:none; border-color:inherit; border-width:0; width:458px; height:65px”class =“style11120” &gt;&lt; / textarea&gt;
&lt; tr&gt;
&lt; td style =“height:53px”&gt;
&lt; div class =“style11116”style =“width:417px”&gt;
&lt; input name =“Submit”type =“submit”value =“submit”/&gt;
&lt; / form&gt;
code> pre>
DIV>
Having some error reporting would tell you that you need ' around the $like
and you need ` around like in the columns section, since like is a reserved word, inside the insert.
mysql_query("INSERT INTO likes (`like`) VALUES ('$like')") or trigger_error('Query Error: ' . mysql_error());
Should work.
Also you will need to enclose the like in ` for the select:
$id = mysql_query("SELECT id FROM likes WHERE `like`=$like") or trigger_error('Query Failed: ' . mysql_error());
Your first SQL query is wrong. You have to enclose string values with quotation marks in SQL:
mysql_query("INSERT INTO likes (`like`) VALUES ('$like')");
The rest of your PHP part will not perform as you wish either. $id will be a resultset, not a value. You'll have to fetch the row like this:
$result = mysql_query("SELECT id FROM likes WHERE `like`='$like'");
$row = mysql_fetch_assoc($result);
$id = $row['id'];
Or even better, just replace the second SQL query with a call to mysql_insert_id:
$id = mysql_insert_id();
Still more possibilities for improvement:
- Don't forget to call
exit
after you've done aheader('Location: ...');
call, otherwise you may get unexpected results since the script will continue running. - Add some error handling of your insert. At least check with an if statement that it succeeded.