使用SQL查询将值数组插入数据库?

时间:2014-02-06 20:07:43

标签: php mysql sql arrays

我的SQL表中有一个PHP列数组。我还有一个我想要分配给这些列的值的数组。我如何将它放在SQL查询中。目前我正在写出每个列标题:

$query = "INSERT INTO `first_page_data`(`a`, `b`, `c`, `d`, `e`, `f`, `g`, `h`) 
VALUES ('$1','$2','$3','$4','$5','$6','$7','$8')";

但必须有一种方法只使用数组?

作为额外的,有没有办法定义键/值对以将两对数据保持在一起,然后使用这些数据插入到数据库中?这是如何在SQL查询中格式化的?

5 个答案:

答案 0 :(得分:6)

这是另一个类似的解决方案。

代码:

<?php
function mysql_insert_array($table, $data, $exclude = array()) {

    $fields = $values = array();

    if( !is_array($exclude) ) $exclude = array($exclude);

    foreach( array_keys($data) as $key ) {
        if( !in_array($key, $exclude) ) {
            $fields[] = "`$key`";
            $values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
        }
    }

    $fields = implode(",", $fields);
    $values = implode(",", $values);

    if( mysql_query("INSERT INTO `$table` ($fields) VALUES ($values)") ) {
        return array( "mysql_error" => false,
                      "mysql_insert_id" => mysql_insert_id(),
                      "mysql_affected_rows" => mysql_affected_rows(),
                      "mysql_info" => mysql_info()
                    );
    } else {
        return array( "mysql_error" => mysql_error() );
    }

}
?>

示例用法:

<?php

// Open database here

// Let's pretend these values were passed by a form
$_POST['name'] = "Bob Marley";
$_POST['country'] = "Jamaica";
$_POST['music'] = "Reggae";
$_POST['submit'] = "Submit";

// Insert all the values of $_POST into the database table `artists`, except
// for $_POST['submit'].  Remember, field names are determined by array keys!
$result = mysql_insert_array("artists", $_POST, "submit");

// Results
if( $result['mysql_error'] ) {
    echo "Query Failed: " . $result['mysql_error'];
} else {
    echo "Query Succeeded! <br />";
    echo "<pre>";
    print_r($result);
    echo "</pre>";
}

// Close database

?>

来源Inserting An Array into a MySQL Database Table

答案 1 :(得分:3)

//Insert ( var , Array )
    function insert($table, $inserts) {
        $values = array_map('mysql_real_escape_string', array_values($inserts));
        $keys = array_keys($inserts);   
        return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
    }
/*  Samples
 insert('first_page_data', array(
    'a' => 'Just Persian Gulf',
    'b' => 'DB9',
    'c' => '2009'
));
*/

这很好,很快!

答案 2 :(得分:0)

使用PHP:

将您的值作为$ key =&gt;获取到数组中$ value取决于具体情况,但手动它会发生如下:

$array = array(`a` => '$1',`b` => '$2', ...and so on); //I am assuming that $ is not a variable indicator since it is inside single quotes.

如果你有一些你宁愿操作以创建最终数组的数组,有很多array functions可以帮助你。

但是,如果你拥有它,那么:

$query = 'INSTERT INTO `first_page_data` (';
foreach ($array as $key => $value) {
    $query .= '`' . $key . '`';
}
$query .= ') VALUES (';
foreach ($array as $value) {
    $query .= '`' . $value . '`';
}
$query .= ')';

代码在数组上运行两次foreach,一次获取密钥并将其附加到字符串的相应部分,另一次添加相应的值。

答案 3 :(得分:0)

在INSERT之前尝试serialize()并在SELECT之后尝试unserialize()以获取数组。

您只需要一个字段即可插入所有数据。

http://ca1.php.net/manual/fr/function.serialize.php
http://ca1.php.net/manual/fr/function.unserialize.php

答案 4 :(得分:0)

# Insert this array
$arr = array("sounds" => "one", "sound" => "two", "big" => "blue");

function addQuotes($str){
    return "'$str'";
}

# Surround values by quotes
foreach ($arr as $key => &$value) {
    $value = addQuotes($value);
}

# Build the column
$columns = implode(",", array_keys($arr));

# Build the values
$values = implode(",", array_values($arr));

# Build the insert query
$query = "INSERT INTO table (".$columns.") VALUES (".$values.")";

echo $query;

// returns
INSERT INTO table (sounds,sound,big) VALUES ('one','two','blue')