Is there a way to make a "universal" php script which works on any form ? Example case : Page A : [Form ] Name : Age : [Submit to page B] Page B : Insert into Mysql Name and Age. I want to know if there is some way to make Page B works for any submitted form, so it doesn't necessarily Name and Age. But the action still same, Insert New Record on MySQL.
It's doable. PHP is very good at reflection. But it probably wouldn't be easy. You'd have to have some context, as in, what type of data should 'age' hold? What table should it go into? And so on. You could do it with a clever use of classes. If you're looking for this sort of thing, though, I'd recommend trying out a framework like CodeIgniter (with the DataMapper library) or Zend. Might as well take advantage of work that's already been done.
$fields = "INSERT INTO table ("; $vals = " VALUES ("; foreach ($_POST as $v => $a) { $fields .= "`$v`,"; $vals .= "'$a',"; } //clean up comers at the end, there's probably a nicer way then this, but this one came to mind $fields = substr($fields,0,strlen($fields)-1); $vals = substr($vals,0,strlen($vals)-1); //close off statement $fields .= ")"; $vals .= ")"; mysql_query($fields.$vals); PHP: should do the trick, you'll want to escape the posted values to avoid injection, though should work
Okay, the code seems good. The code basically parsing the field and value into mysql insert script. But how to use it? Can you give me the example on my case ?
put the code into a script file i.e. adder.php and make the form side point something like <form action="adder.php" method="post">
for the form would be something like echo '<form action="adder.php" method="post">'; $qid = mysql_query("DESCRIBE ".$table); while ($res = mysql_fetch_array($qid)) { echo "<input name=\"$res[Field]\" type=\"text\"/>"<br/>"; } echo '<input type="submit" value="submit" name="submit" />'; echo "</form>"; PHP: