I’m trying to make a very basic comment system in PHP.
The problem is that when I submit the form, the new row doesn’t get inserted in my MySQL table.
This is my code (, could someone please check what’s wrong?):
<?php
$act = $_POST['act'];
if($act == 1) {
$m = $_POST['message'];
$m = strip_tags($m);
$message = mysql_real_escape_string($m);
$name = "Anonymous"; //Static username for demonstration purposes
$date = "2012-7-28"; //Static date for demonstration purposes
$con = mysql_connect("localhost","username","password");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_query("INSERT INTO comments (name, message, date) VALUES ('$name', '$message', '$date')");
mysql_close($con);
}
?>
<form action="comments.php" method="post">
<input type="text" name="message">
<input type="hidden" name="act" value="1">
<input type="submit" name="submit" value="Submit">
</form>
I think your problem rests with the escaping, or rather the ‘non-escaping’ of the column names. Did you know that ‘date’ is a function name in mySQL?
Try putting all table and column names in backticks.
Also, for further reference, posting the error message never hurts looking for the answer.
Other than that, I can’t find anything particularly wrong with your query.
Edit: DUH! I missed something obvious.
Please execute ‘mysql_select_db(‘name_of_database’); prior to the query.
Otherwise it won’t know where to look for the table you’re specifying.
For the sake of completeness (as Michael Besteck pointed out), it is necessary to execute ‘mysql_real_escape_string’ only AFTER the connection has been established.
That is, because the ‘escape_string’ relies on the encoding of the connection to determine which characters need to be escaped and how.