Page 1 of 1

Getting Undefined Variable Error What am I doing Wrong ?

Posted: Mon Aug 30, 2010 11:15 am
by VR-Fox
I have a simple php code that creates tables in my database. I have a basic form where you can type in a table name and click submit and it will create a new table in the database with the specified name the user input into the textbox on the webform.
However.... I keep getting this error...

Notice: Undefined variable: tablename in C:\wamp\www\workspace\AAA\newfile.php on line 24
Database access failed: Incorrect table name ''

The strange thing is even though I get this error it still creates the table in the database.

Can someone please tell me where my syntax is wrong on line 24 ...here is my php code

----------------------------------
<?php
require_once 'login.php';

$db_server = mysql_connect($db_hostname, $db_username, $db_password);

if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());

mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());


if (isset($_POST['tablename']))
{
$tablename = get_post('tablename');
}

echo <<<_END
<form action="newfile.php" method="post"><pre>
Table Name: <input type="text" name="tablename" />
<input type="submit" value="ADD TABLE" />
</pre></form>
_END;

$query = "CREATE TABLE `$tablename` (family VARCHAR(32) NOT NULL)";

$result = mysql_query($query);

if (!$result) die ("Database access failed: " . mysql_error());

mysql_close($db_server);

function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>

Re: Getting Undefined Variable Error What am I doing Wrong ?

Posted: Mon Aug 30, 2010 11:27 am
by AbraCadaver
You need to put your query inside the if isset() block or else it will run even when $tablename is not set. I'd probably do it more like this:

Code: Select all

if ($tablename = get_post('tablename')) {
	$query = "CREATE TABLE `$tablename` (family VARCHAR(32) NOT NULL)";	
	$result = mysql_query($query);	
	if (!$result) die ("Database access failed: " . mysql_error());	
	mysql_close($db_server);
}

echo <<<_END
<form action="newfile.php" method="post"><pre>
Table Name: <input type="text" name="tablename" />
<input type="submit" value="ADD TABLE" />
</pre></form>
_END;

function get_post($var) {
	if(isset($_POST[$var]) && !empty($_POST[$var])) {
		return mysql_real_escape_string($_POST[$var]);
	}
	return false;
}