RightMove数组 - 插入列tItles和值MySQL

时间:2012-01-24 09:55:51

标签: php sql arrays

我非常容易陷入非常容易的事情。我试图使用http://kodegeek.wordpress.com/2010/02/20/rightmove-data-parsing-php-class/

中的PHP类解析.BLM文件

Class完美运行并输出如下数组: -

Array ( [0] => Array ( [AGENT_REF] => _70 [ADDRESS_1] => 123 Main Street [POSTCODE1] => CF12 [POSTCODE2] => 4HY [FEATURE1] => Ideal Location [FEATURE2] => Only £250 per room [FEATURE3] => Three Double Bedrooms ) [2] => Array ( [AGENT_REF] => _83 [ADDRESS_1] => 45 Harriet Street [POSTCODE1] => CF24 [POSTCODE2] => 4BU [FEATURE1] => Modern [FEATURE2] => Laminate Flooring ) )

创建数组后,我想立即将数组插入SQL表中。理想情况下,这将获得Field标题,例如。 [AGENT_REF] [ADDRESS_1]并创建列并将数据作为每个数组的新行插入([0] =>数组[2] =>数组)等。

我尝试了类似这样的事情和许多其他变体,我似乎无法让它发挥作用。

function mysql_insert_array($table, $rmdata) {
foreach ($rmdata as $field=>$value) {
 $fields[] = '`' . $field . '`';
 $values[] = "'" . $value . "'";

}
$field_list = join(',', $fields);
$value_list = join(', ', $values);



$query = "INSERT INTO testarray (" . $field_list . ") VALUES (" . $value_list . ")";

3 个答案:

答案 0 :(得分:1)

在插入之前,必须使用字段列表创建表。 如果您没有创建表,可以使用:

$sql = "CREATE TABLE if not exists TABLENAME ( 
    id tinyint(4) unsigned NOT NULL auto_increment, 
    AGENT_REF varchar(80) NOT NULL, 
    ADDRESS_1 varchar(255),
    POSTCODE1 varchar(6),
    POSTCODE2 varchar(6),
    FEATURE1 varchar(255),
    FEATURE2 varchar(255),
    FEATURE3 varchar(255),
    PRIMARY KEY (id) 
    )"; 

mysql_query($sql,$link); 

并在你的功能之后。

答案 1 :(得分:1)

<?php

$rmdata = ARRAY();

$rmdata[0]['field1'] = 1;
$rmdata[0]['field2'] = 'two';
$rmdata[0]['field3'] = 3;
$rmdata[0]['field4'] = NULL;
$rmdata[0]['field5'] = 'five';
$rmdata[1] = $rmdata[2] = $rmdata[3] = $rmdata[0];

foreach ($rmdata AS $key => $dummy) {

  $fields = ARRAY();
  $values = ARRAY();

  foreach ($rmdata[$key] as $field=>$value) {
    if (!isset($value)) {
      //$value='';
      // or
      //if($field=='field4') { $value=4; }
      // or $values[] = "NULL";
    }

    if (isset($value)) {
      $fields[] = $field;
      $values[] = "'".$value."'";
    }
  }
  // if (count($fields) > 0)
  echo 'key: '.$key.'<br />';
  $sql_fields = implode(',', $fields);
  $sql_values = implode(',', $values);
  print_r($sql_fields); echo '<br />';
  print_r($sql_values); echo '<hr />';

}    

?>

答案 2 :(得分:0)

$rmdata = ARRAY();

$rmdata['field1'] = 1;
$rmdata['field2'] = 'two';
$rmdata['field3'] = 3;
$rmdata['field4'] = NULL;
$rmdata['field5'] = 'five';

$fields = ARRAY();
$values = ARRAY();
foreach ($rmdata as $field=>$value) {
  if (!isset($value)) {
    //$value='';
    // or
    //if($field=='field4') { $value=4; }
    // or $values[] = "NULL";
  }

  if (isset($value)) {
    $fields[] = $field;
    $values[] = "'".$value."'";
  }

}

// if (count($fields) > 0)
$sql_fields = implode(',', $fields);
$sql_values = implode(',', $values);