user3533863 user3533863 - 6 months ago 12
SQL Question

MySQL - PHP form to insert values into table?

I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:

<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());

$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];

$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";

mysql_close($connection); // Closing Connection

?>


Thank you for your help!

Answer

You don't ever actually execute your query:

$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);

Other things:

  1. if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.

  2. Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

  3. You are also wide open to SQL injections

  4. You do no error checking. How do you expect to know if there are problems if you don't look for them?