-1
$dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = '';
    $conn = mysql_connect($dbhost, $dbuser, $dbpass);
    if(! $conn )
    {
      die('Could not connect: ' . mysql_error());
    }

    echo 'Connected successfully<br />';



$name_of_field="id_student";


function field_dynamic($field_num,$field_name){

    for($i=1;$i<=$field_num;$i++){

        if($i!=$field_num){

        $field[$i]="".$field_name."_".$i." VARCHAR(5) NOT NULL,"."";

        }else{

        $field[$i]="".$field_name."_".$i." VARCHAR(5) NOT NULL";

        }

    }
    return $field;
}

$num=13;

$sql_mathematic = "CREATE TABLE mathematic(". 

            field_dynamic($num,$name_of_field).")";

        mysql_select_db("adrian");
        $retval_mathematic = mysql_query( $sql_mathematic, $conn );

        if(! $retval_mathematic )
            {
              die('Could not create table: ' . mysql_error());
            }

            echo "Table created successfully\n";

its not working:

Connected successfully
Could not create table: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1

Please help me.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Try to debug by printing the content of $field, to see what is wrong with that Sql statement that is now executed, than let see. – Dynamikus Jun 21 '11 at 17:52
  • Just out of interest: what are you trying to do? It looks like a strange database design to me.. – konsolenfreddy Jun 21 '11 at 17:55
  • print the complete query and you'll find what's wrong near ')'. What you are returning from the function is the $field array - how are you passing it to the query? Are you looping through $field array or imploding it or what? – Abhay Jun 21 '11 at 18:07

1 Answers1

2

This would accomplish what you are talking about, but you shouldn't use it.

for($i=1;$i<=$field_num;$i++){
    $field[$i]="".$field_name."_".$i." VARCHAR(5) NOT NULL";

}
return implode(',',$field);
miken32
  • 42,008
  • 16
  • 111
  • 154
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166