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]);
}
?>
Getting Undefined Variable Error What am I doing Wrong ?
Moderator: General Moderators
- AbraCadaver
- DevNet Master
- Posts: 2572
- Joined: Mon Feb 24, 2003 10:12 am
- Location: The Republic of Texas
- Contact:
Re: Getting Undefined Variable Error What am I doing Wrong ?
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;
}mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.