【问题标题】:Auto generate array from column从列自动生成数组
【发布时间】:2013-12-05 04:43:21
【问题描述】:

我正在制作一个从给定数据库和表构建自身的表单。但是,当涉及到插入功能时,我遇到了一个障碍。我已经做到了,以便所有字段都生成输入,textareas 你在页面上具有正确名称的内容。现在我需要做的就是将它插入到数据库中。但我需要使用 implode 以 (this,that,this) 格式重新创建数组,但我不知道该怎么做。

 $resultInsert = mysql_query("SHOW COLUMNS FROM " . $table);
$fieldnames=array();

if (mysql_num_rows($resultInsert) > 0) {
        while ($row = mysql_fetch_array($resultInsert)) {
            echo $fieldnames[] = $row['Field']; #currently outputting titlebodytextcreated (three fields i have)
        }
      }


// FORMAT: field_name = $_POST[fieldname]

$values = array('title'=>$_POST['title'],'bodytext'=>$_POST['bodytext']); # need this to be autogenerated by the field names

echo "<br>" . sprintf('INSERT INTO %s (%s) VALUES ("%s")', 'testdb', 
implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values))); 

// add loop for id to be generated in a hidden field, along with all other excluded fields so that the
// update will process correctly in the insert into phase

【问题讨论】:

  • 这真的很困扰我哈哈。我对 php 有点菜鸟。但我真的想让这段代码工作

标签: php arrays populate


【解决方案1】:

这行得通吗?

$values = array_intersect_key( $_POST, array_flip($fieldnames) );

或者,如果您想确保$fieldnames 中的所有值在$values 中都有一个键,即使$_POST 中的对应键为空:

$values  = array_flip($fieldnames);  
$values += array_intersect_key( $_POST, $values );

【讨论】:

猜你喜欢
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多