Jump to content

Not Creating table correctly


Farside

Recommended Posts

I am just really trying to get familiar with PHP and MySQl.  I have been able to connect and create a database properly and now when trying to just create a table it won't work.  Here is the coding that i have.  It is the third set of codes, it has two prior sets thats connected to it.

 

<?php
$db_name = "testdb";
$connection = mysql_connect("localhost","jcruz","abc2000") or die(mysql_error());
$db = mysql_select_db($db_name,$connection) or die(mysql_error());
$sql ="CREATE TABLE $_POST[table_name] (";

for ($i = 0; $i < count($_POST[field_name]); $i++) {
$sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i];

if ($_POST[field_length][$i] != "") {
	sql .= " (".$_POST[field_length][$i]."),";
} else {
	$sql .= ",";
}
}

$sql = substr($sql, 0, -1);
$sql .= ")";
$result = mysql_query($sql,$connection) or die(mysql_error());

if ($result) {
$msg = "<P>".$_POST[table_name]." has been created!</P>";
}

?>

<HTML>
<HEAD>
<TITLE>Create a Database Table: Step 3</TITLE>
</HEAD>
<BODY>

<H1>Adding Table to <?php echo "$db_name"; ?>...</H1>

<?php echo "$msg"; ?>

</BODY>
</HTML>

Link to comment
https://forums.phpfreaks.com/topic/76466-not-creating-table-correctly/
Share on other sites

Instead of....

 

$result = mysql_query($sql,$connection) or die(mysql_error());

 

Use....

 

$result = mysql_query($sql,$connection) or die(mysql_error()."<br />$sql");

 

This should give you an indication of what your query actuyally looks like.

 

ps: Be aware that associative arrays are indexed by strings, hence you need (should) use $_POST['field_name'] instead of $_POST[field_name]. And if your going to place them within double quotes for variable interpolating they need be....

 

"CREATE TABLE {$_POST['table_name']} (";

 

and not....

 

"CREATE TABLE $_POST[table_name] (";

 

I'm not even going to get started on validating form data before you let it anywhere near your queries. I'll simply put it this way.... the code you have is very insecure and could lead to entire databases being deleted quite easily.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.