PHP Form writes blank row to MySQL DB
I'm using a simple form to submit a row to my database. I don't get an error connecting to the database and it does inserts the row but it writes all values blank.
This is the form:
<form action="in开发者_运维技巧sert.php" method="post">
Título: <input type="text" name="title" />
Privacidad: <select type="text" name="privacy" />
<option value="public">Publico</option>
<option value="private">Privado</option>
</select><br/>
<input type="submit" />
</form>
And this is the insert.php file:
<?
$con = mysql_connect("removed","removed","removed");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("copoetry", $con);
$sql="INSERT INTO Poems (Title, Privacy)
VALUES
('$_POST[title]','$_POST[privacy]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
What am I doing wrong? Thanks
Just assign $_POST variables instead of trying to inline them into the statement. You will also have to escape whatever quotes may appear inside the POST data. So, do this:
$title = mysql_real_escape_string($_POST['title']);
$privacy = mysql_real_escape_string($_POST['privacy']);
$sql="INSERT INTO Poems (Title, Privacy)
VALUES
('$title','$privacy')";
Also, changing stuff to "'$_POST['title']','$_POST['privacy']'
" won't work at least because to inline array values to a string, you have to use {}
like $correct_string = "Hello {$_POST['world']}"
yes you should change the $_POST[title] and $_POST[privacy] to $_POST['title'] and $_POST['privacy'] .
and also change : <select type="text" name="privacy" />
to <select name="privacy" >
you could do this:
$sql="INSERT INTO Poems (Title, Privacy)
VALUES
('".$_POST['title']."','".$_POST['privacy']."')";
or:
$sql="INSERT INTO Poems (Title, Privacy)
VALUES
('{$_POST['title']}','{$_POST['privacy']}')";
should work, your problem is coming from the quotation marks. Find a way to get around them and you are done.
Leaving aside the GLARING PROBLEM of SQL injection / badly formed SQL, this should work as long as the values don't contain any single quotes.
Try writing $sql and var_export($_POST,true) to your log file for each operation to see what's actually happening.
精彩评论