数组键作为插入的mysql列名?

时间:2012-11-20 18:38:20

标签: php mysql

我正在使用一个将搜索结果作为json返回的API。然后,我需要将其写入MYSQL表。我以前成功完成了这个,但这次情况有所不同,我认为这是因为结果数组的结构:键名是动态的,如果没有特定键的数据,键不是在数组中列出。以下是数组的示例vardump:

array
  0 => 
    array
      'title' => string 'Funny but not funny' (length=19)
      'body' => string 'by Daniel Doi-yesterday while eating at Curry House...
      'url' => string 'http://danieldoi.com/2012/11/20/funny-but-not-funny/' 
      'source_site_name' => string 'WordPress.com' (length=13)
      'source_site_url' => string 'http://www.wordpress.com' (length=24)
      'query_topic' => string 'thanksgiving' (length=12)
      'query_string' => string 'blogs=on&topic=thanksgiving&output=json' (length=39)
  1 => 
    array
      'title' => string 'Travel Easy this Holiday Season...' (length=34)
      'body' => string 'Give yourself a few gifts and get this holiday season off...
      'url' => string 'http://facadebeauty.wordpress.com/2012/11/20
      'date_published' => string 'Tue, 20 Nov 2012 18:22:35 +0000' (length=31)
      'date_published_stamp' => string '1353435755' (length=10)

请注意密钥的顺序/包含如何变更。

我建议的解决方案是使用数组键作为列名,将它们变成一个变量以在查询语句中使用,但这对我不起作用。这是我的尝试:

$jsonString = file_get_contents("http://search-query-URL&output=json");
$array = json_decode($jsonString, true);

// database connection code snipped out here

$table = "results";

foreach($array as $arr_value) {
        foreach ($arr_value as $value) {
          $colName = key($arr_value);
          $colValue = ($value);
          $insert="INSERT INTO $table ($colName) VALUES ('$colValue')";

          mysql_query($insert) OR die(mysql_error());
          next($arr_value);
              }
         }

关于下一步要去哪里的建议?谢谢!

更新11/27:

我在这里试图改变大卫的建议。我收到以下错误:“数据库连接错误(1110)列'标题'在查询时指定了两次。”

这是我现在的代码:

$mysqli = mysqli_connect("localhost");
mysqli_select_db($mysqli, "mydatabase");

foreach ($array as $column) {
    foreach ($column as $key => $value) {
    $cols[] = $key;
    $vals[] = mysqli_real_escape_string($mysqli, $value);
    }
}

$colnames = "`".implode("`, `", $cols)."`";
$colvals = "'".implode("', '", $vals)."'";
$mysql = mysqli_query($mysqli, "INSERT INTO $table ($colnames) VALUES ($colvals)") or die('Database Connection Error ('.mysqli_errno($mysqli).') '.mysqli_error($mysqli). " on query: INSERT INTO $table ($colnames) VALUES ($colvals)");
mysqli_close($mysqli);
if ($mysql)
return TRUE;
else return FALSE;

最终升级 - 工作!

它正在运作。这是我们得到的:

$mysqli = mysqli_connect("localhost");
mysqli_select_db($mysqli, "mydatabase");
  foreach ($array as $column) {
foreach ($column as $key => $value) {
    $cols[] = $key;
    $vals[] = mysqli_real_escape_string($mysqli, $value);
    }
  $colnames = "`".implode("`, `", $cols)."`";
  $colvals = "'".implode("', '", $vals)."'";
  $mysql = mysqli_query($mysqli, "INSERT INTO $table ($colnames) VALUES ($colvals)") or die('Database Connection Error ('.mysqli_errno($mysqli).') '.mysqli_error($mysqli). " on query: INSERT INTO $table ($colnames) VALUES ($colvals)");

  unset($cols, $vals);
}
  mysqli_close($mysqli);
if ($mysql)
return TRUE;
else return FALSE;  

3 个答案:

答案 0 :(得分:5)

我实际上只有这个功能,因为我一直都在使用它。这样做:汇集数组中的所有关联对以插入表中,并将它们作为单个插入放入。要明确:这不是你上面所做的,因为看起来你正试图在每个插入的插入中插入每个值,这可能会给你更多的行。

function mysqli_insert($table, $assoc) {
    $mysqli = mysqli_connect(PUT YOUR DB CREDENTIALS HERE);
    mysqli_select_db($mysqli, DATABASE NAME HERE);
    foreach ($assoc as $column => $value) {
        $cols[] = $column;
        $vals[] = mysqli_real_escape_string($mysqli, $value);
    }
    $colnames = "`".implode("`, `", $cols)."`";
    $colvals = "'".implode("', '", $vals)."'";
    $mysql = mysqli_query($mysqli, "INSERT INTO $table ($colnames) VALUES ($colvals)") or die('Database Connection Error ('.mysqli_errno($mysqli).') '.mysqli_error($mysqli). " on query: INSERT INTO $table ($colnames) VALUES ($colvals)");
    mysqli_close($mysqli);
    if ($mysql)
        return TRUE;
    else return FALSE;
}

正如MarcB上面所说,您的目标表可能没有结果显示的列。但我们正在对插入进行消毒(使用mysqli_real_escape_string),因此我们不应该遇到注入漏洞问题。

答案 1 :(得分:1)

这是单行:

$query = 'INSERT INTO '.$table.'(`'.implode('`, `', array_keys($array)).'`) VALUES("'.implode('", "', $array).'")';

答案 2 :(得分:0)

我注意到上面发布了一个答案,但是因为我已经写了这个,所以我想发布它。注意:我希望您信任从哪里获取数据,否则会出现各种问题。我还在整个代码中添加了注释,希望有助于理解它是如何完成的。

$jsonString = file_get_contents("http://search-query-URL&output=json");
$array = json_decode($jsonString, true);

// database connection code snipped out here

$table = "results";

foreach($array as $sub_array) {
    // First, grab all keys and values in separate arrays
    $array_keys = array_keys($sub_array);
    $array_values = array_values($sub_array);

    // Build a list of keys which we'll insert as string in the sql query
    $sql_key_list = array();
    foreach ($array_keys as $key){
        $sql_key_list[] = "`$key`";
    }
    $sql_key_list = implode(',', $sql_key_list);

    // Build a list of values which we'll insert as string in the sql query
    $sql_value_list = array();
    foreach ($array_values as $value){
        $value = mysql_real_escape_string($value);
        $sql_value_list[] = "'$value'";
    }
    $sql_value_list = implode(',', $sql_value_list);

    // Build the query
    $insert = "INSERT INTO $table ($sql_key_list) VALUES ($sql_value_list)";
    mysql_query($insert) or die(mysql_error());
}