Re: Dynamically generating PHP functions?

From: Date: Fri, 15 Sep 2000 06:04:04 +0000
Subject: Re: Dynamically generating PHP functions?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-16933@lists.php.net to get a copy of this message
On Fri, 15 Sep 2000, Joseph H Blythe wrote: > I have written a script that dynamically generates a form from a given > database and table that would be suitable, as a generic data input > device for any mysql table. > > My problem is that when I have tried to write the script for the forms > action i.e.: > > ... > mysql("database","INSERT INTO table Values ( > '$field1', > '$field2', > '$field3', > '$field4' > )"); > > > I cannot figure out how to generate the above function dynamically so > that that it has the correct number of fields for the given database > table, does anyone know how one would go about writing php functions > dynamically then executing them? Why not write your function to accept an array of the fields? That would enable you to pass it any number of fields, and a single function could handle it. One downside is it'd mean naming all your form fields in some form, like value="fields[username]", value="fields[first_name]", etc., or processing the form data into an array before calling the insert function. The function may look something like this (Untested) function insertdata($tablename,$fields) { $fieldcount = count($fields); $sql = "INSERT INTO $tablename VALUES ("; for ($i = 0; $i < $fieldcount; $i++) { $sql .= '"' . $fields[$i] . '"'; if ($i < $fieldcount - 1) $sql .= ','; $sql .= ')'; } mysql_query($sql); } Matt

« previous php.general (#16933) next »