Hey there. I'm having a bit on an issue with adding new data to an SQL table on my webserver. I'm trying to update data in the table through php, but for an unknown reason the script returns no errors but refuses to update the SQL table with the content I provide.

<?php
  $databasename = $_POST["databasename"];
  $databaseuser = $_POST["databaseuser"];
  $databasepass = $_POST["databasepass"];

  $connection = mysql_connect("localhost", $databaseuser, $databasepass);

  if (!$connection) {
    echo "A connection could not be made to the database! Possible issues: Your username and/or password may have been incorrect!";
    return;
  }

  $seldb = mysql_select_db($databasename, $connection);

  if (!$seldb) {
    echo "An error occured while selecting the database!";
    return;
  }

  $tablename = $_POST["tablename"];

  if (!tableExists($tablename)) {
    echo "The table name you entered doesn't exist!";
    return;
  }

  $tablecol = $_POST["colname"];
  $tablecoldat = $_POST["coldata"];

  if (!$tablecol) {
    echo "You must enter a collumn name to enter data into!";
    return;
  }
  $req =
  "INSERT INTO " . $tablename . " (
    '" . $tablecol . "'
  )
  VALUES (
    '" . $tablecoldat . "'
  )";
  mysql_query($req, $connection);
  mysql_close();
  echo "Script end!";

  /*
    FUNCTIONS
  */
  function tableExists($tbl) {
    global $connection;
    $dat = mysql_query("SELECT * FROM " . $tbl, $connection);
    if (!$dat) {
      return false;
    } else {
      return true;
    }
  }
?>

I'm pretty new to PHP, and I've only been studying it for a couple of days so I apologize if my code seems messy, inefficient or just plain garbage. Help would be appreciated if you can give it though. If you need any more information on what I'm doing just ask. As far as I know this is all I need to post.

The database name: aaron_test_database
The table name: aaron_test_table

Try to change quotes with backticks in the field names of the INSERT statement, as here:

$req = "INSERT INTO $tablename(`$tablecol`) VALUES ('$tablecoldat')";

Also, to catch an error use mysql_error() at least in this stage:

 mysql_query($req, $connection) or die(mysql_error());

That's fantastic. Thanks for your help! I edited my code to match the first sample you posted, and it worked fantasically.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.