最佳实践:将大型表单值存储到数据库中 [英] Best Practice : Store Large Form Values into Database

查看:140
本文介绍了最佳实践:将大型表单值存储到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个大的表单,包括文本框,单选按钮,复选框,选择标签,textareas等25个字段。

一旦表单被提交,什么将是收集这些值并将其存储到数据库中的最佳方式;通过最佳实践,我的意思是使用尽可能少的代码行

传统的方式: / p>

  $ name = $ _POST ['name']; 
$ age = $ _POST ['age'];
$ city = $ _POST ['city'];

这绝对不是路要走。



有另一种方法:

  foreach($ _POST ['submit'] as $ key => $ val)
{
$$ key = $ val;





但是这又需要一个巨大的INSERT SQL语句:


$ b

 INSERT INTO表名(col1,col2,col3,col4,... col25)
VALUES '$ var1','$ var2','$ var3',.....'$ var25')

使用 foreach来捕获值是很好的,但是它带有一个拉长的SQL INSERT语句。我确定有一个更好的方法来使用INSERT语句。想法,建议,批评都欢迎。

谢谢,
Nisar

在HTML中的变化如下


 < input type =textname =pval [name] value =test/> 
< input type =cityname =pval [city]value =Bangalore/>

然后在服务器端



  //需要预定义的数组有$ field 
$ fields = array('name','city');

$ pval = $ _POST ['pval'];
foreach($ pval as $ field_name => $ val){

if(!isset($ fields [$ field_name])){//如果不是有效的字段名

unset($ pval [$ field_name]);



$ b if(count($ pval)> 0){

$ pval = array_map('mysql_real_escape_string' ,$ pval);

//然后它很容易编写如下查询

$ qry =INSERT INTO table_name(。implode(',',array_keys($ pval))。 )values('。implode(',',$ pval)。');
}


Suppose I've a large form, 25 fields consisting of textboxes, radio buttons, checkboxes, select tags, textareas etc.

Once the form is submitted, what would be the best way to collect those values and then store them into database; by best practice I mean using as minimal lines of code as possible.

There is the traditional way:

$name = $_POST['name'];
$age = $_POST['age'];
$city = $_POST['city'];

which is definitely not the way to go.

There is then another way :

foreach($_POST['submit'] as $key=>$val)
{
 $$key = $val;
}

but again this will require a huge INSERT SQL statement:

"INSERT INTO tablename (col1, col2, col3, col4,...col25)
 VALUES('$var1', '$var2', '$var3',.....'$var25')"

Using foreach to capture values is good, but then it comes with an elongated SQL INSERT statement. I'm sure there must a better way to use the INSERT statement. Ideas, suggestions, critics are all welcome.

Thanks, Nisar

解决方案

In HTML change as follows

<input type="text" name="pval[name]" value="test" />
<input type="city" name="pval[city]" value="Bangalore" />

Then in the server side

Updated :

// Need to have the predefined array which is having valid fields
$fields = array('name', 'city');

$pval = $_POST['pval'];
foreach( $pval as $field_name => $val ){

   if( ! isset($fields[$field_name]) ){ // If it is not a valid field name

      unset($pval[$field_name]);
   }

}

if( count($pval) > 0 ){

$pval = array_map( 'mysql_real_escape_string', $pval );

//Then its easy to write the query as follows

    $qry = "INSERT INTO table_name( ". implode( ',', array_keys( $pval ) ) .") values( '". implode( "','", $pval ) . "')";  
}

这篇关于最佳实践:将大型表单值存储到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆