Why is it not saving on the database?
I have an input form for a sample php.
<form action="insert.php" method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" id="fname" name="fname" /></td>
</tr>
<tr>
<td>Last Name:</td开发者_JS百科>
<td><input type="text" id="lname" name="lname" /></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" id="age" name="age" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Add Person!" /></td>
</tr>
</table>
</form>
and the insert.php goes like this
<?php
$host = "localhost";
$user = "root";
$pass = "";
$con = mysql_connect($host, $user, $pass);
$db = "phptest";
if(!$con)
{
die("Could not connect: " . mysql_error());
}
mysql_select_db($db,$con);
$sql = "INSERT INTO persons (FirstName,LastName,Age) VALUES ('$_POST[fname]','$_POST[lname]','$_POST[age]')";
mysql_query($sql,$con);
mysql_close($con);
?>
It works fine for the first input. When I input another values and press the submit button, the data is not saving into the database. In the database, it only shows 1 row filled with my first input. What's the problem on the code for insert.php? Thanks.
Please also do
echo mysql_error();
right after mysql_query() to know if something is wrong, although your query seems pretty fine.
Also, posting your table structure might help. *It might be that you forgot to have an id in your table that is set to primary_key and auto_increment*
My best guess is that you're passing data into the query that has a single quote in it, which is prematurely causing one of your quoted strings in the query to end.
Without knowing what the exact error is, I can't be sure though. You should be checking for errors with something like mysql_error()
. If you use that and show your error message, I'll be able to help you more.
Tossing data directly from user input (which is what $_POST
contains) is a Very Bad Idea. You're better off using PDO and prepared statements.
Rather than writing a whole rant on this again, I'll just direct you to an answer I wrote the other day. You can find it here.
Create a new field (ex: Id
) in your table persons
and set it to auto_increment
.
精彩评论