Greetings...
The following is the _third_ part of a script found in Julie Meloni's book
"PHP Essentials" on page 118.

The script dynmically generates a form box of field names, field types and
field sizes for a mysql table depending on what the user chooses.

My question is about syntax or logic in the following snippet:

The variables:
$field_name
$field_type
$field_length

are carried over from the previous script.

.............................................

$sql = "CREATE TABLE $table_name (";

   for ($i = 0; $i < count($field_name); $i++) {

  $sql .= "$field_name[$i] $field_type[$i]";

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

 $sql = substr($sql, 0, -1);

 $sql .= ")";

...........................................

My question is about the snippet:

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

In that it would say that if the field_length variable is not empty then add
the (number) and comma to the sql statement

If it is empty, then just add a comma.

The question:

Is the reasoning that a comma *must* be added since this is _within_ a loop?

As in:
CREATE TABLE chairs (
id INT(5),
item VARCHAR(50),
desc TEXT ,
price FLOAT , // common should be deleted but there is no way of knowing
this within the loop.
                      // that's why after the loop closes there is a
substr() function to delete the comma.
);


And that after the loop ends, the comma is then deleted using the substr()
function to complete the sql statement.

TIA,
Tony Ritter
..........................................................................

The complete script:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>Create a Database Table: Step 3</TITLE>
<style>
p {font-family:arial;
    font-size: .75em;}

input {border: 1px solid black;}

th {font-family:arial;
    font-size: .75em;
    color:red;}

h2 {font-family:arial;
    font-size: 1em;}
</style>


</HEAD>
<BODY>

<h2>Adding <?php echo "$table_name"; ?> Table</h2>

<?

 $sql = "CREATE TABLE $table_name (";

   for ($i = 0; $i < count($field_name); $i++) {

  $sql .= "$field_name[$i] $field_type[$i]";

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

 $sql = substr($sql, 0, -1);

 $sql .= ")";

 $connection = mysql_connect("","","")
  or die("Couldn't connect to server.");

 $db = mysql_select_db("database", $connection)
  or die("Couldn't select database.");

 $sql_result = mysql_query($sql,$connection)
  or die("Couldn't execute query.");

 if (!$sql_result) {
  echo "<P>Couldn't create table!";
 } else {
  echo "<P>$table_name [table] has been created!";
 }



?>


</BODY>
</HTML>





-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to