I do not think that this has been posted before – as this is a very specific problem.
I have a script that generates a “create table” script with a custom number of columns with custom types and names.
Here is a sample that should give you enough to work from –
$cols = array();
$count = 1;
$numcols = $_POST['cols'];
while ($numcols > 0) {
$cols[] = mysql_real_escape_string($_POST[$count."_name"])." ".mysql_real_escape_string($_POST[$count."_type"]);
$count ++;
$numcols --;
}
$allcols = null;
$newcounter = $_POST['cols'];
foreach ($cols as $col) {
if ($newcounter > 1)
$allcols = $allcols.$col.",\n";
else
$allcols = $allcols.$col."\n";
$newcounter --;
};
$fullname = $_SESSION['user_id']."_".mysql_real_escape_string($_POST['name']);
$dbname = mysql_real_escape_string($_POST['name']);
$query = "CREATE TABLE ".$fullname." (\n".$allcols." )";
mysql_query($query);
echo create_table($query, $fullname, $dbname, $actualcols);
But for some reason, when I run this query, it returns a syntax error in MySQL. This is probably to do with line breaks, but I can’t figure it out. HELP!
You have multiple SQL-injection holes
mysql_real_escape_string()only works for values, not for anything else.Also you are using it wrong, you need to quote your values aka parameters in single quotes.
If you don’t
mysql_real_escape_string()will not work and you will get syntax errors as a bonus.In a
CREATEstatement there are no parameters, so escaping makes no sense and serves no purpose.You need to whitelist your column names because this code does absolutely nothing to protect you.
Coding horror
see this question for answers:
How to prevent SQL injection with dynamic tablenames?
Never use
\nin a queryUse separate the elements using spaces. MySQL is perfectly happy to accept your query as one long string.
If you want to pretty-print your query, use two spaces in place of
\nand replace a double space by a linebreak in the code that displays the query on the screen.More SQL-injection
$SESSION['user_id']is not secure, you suggest you convert that into an integer and then feed it into the query. Because you cannot check it against a whitelist and escaping tablenames is pointless.Surround all table and column names in backticks
`This is not needed for handwritten code, but for autogenerated code it is essential.
Example:
Learn from the master
You can generate the create statement of a table in MySQL using the following MySQL query:
Your code needs to replicate the output of this statement exactly.