0

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

2
Contributors
2
Replies
7
Views
4 Years
Discussion Span
Last Post by Aaron_JY
1

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());

Edited by cereal

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.