如何将数组发布到MySQL

时间:2011-03-26 21:04:56

标签: php mysql

我们如何将以下数组发布到mysql(列:id,date,amount)......

Array
(
   [date] => Array
   (
      [0] => 03/27/2011
      [1] => 04/27/2011
    )
   [amount] => Array
   (
      [0] => 5000
      [1] => 5000
    )
)

我们如何从这个数组中获取数据(日期和数量)以使用foreach发布intomysql?

我们使用以下字段获取此数组btw ...

<input type="text" name="payment[date][]" /> <input type="text" name="payment[amount][]" />
<input type="text" name="payment[date][]" /> <input type="text" name="payment[amount][]" />

感谢您的支持。

4 个答案:

答案 0 :(得分:3)

循环遍历第一个子阵列,并保持$i索引访问第二个子阵列:

$stmt = $pdo->prepare("INSERT INTO things (date,amount) VALUES (?,?)");

foreach ($array["date"] as $i=>$_ignore)
{
    $stmt->execute( array($array["date"][$i], $array["amount"][$i]) );
}

答案 1 :(得分:1)

试试这个:

<?php
$arr = $_POST['payment'];
$insert = array();
foreach($arr['date'] as $key => $date){
   $date = mysql_real_escape_string($date);
   $amount = (int)$arr['amount'][$key];
   $insert[] = "('$date', $amount)";
}

mysql_query("INSERT INTO table(date, amount) VALUES " 
    . implode(",", $insert));

答案 2 :(得分:1)

这是一个mysqli版本(未经测试,我从不使用mysqli,但我认为应该工作)

// the sql statement for the insert
$sql = 'INSERT INTO yourTable ( `id`, `date`, `amount` ) VALUES( null, ?, ? )';

// prepare the query for binding to the placeholders later on
$stmt = $mysqli->prepare( $sql );

// bind some variables to the placeholders
$stmt->bind_param( 'si', $date, $amount );

// loop through all date values
foreach( $yourArray[ 'date' ] as $key => $value ) )
{
    // check if there is an equivalent index in $yourArray[ 'amount' ]
    // change to isset if you want to guard againt null values
    if( !array_key_exists( $key, $yourArray[ 'amount' ] ) )
    {
        // throw an exception of perhaps use some other form of error
        throw new Exception( 'missing parameter' );
    }

    // give the previously bound variables values for this query execution
    $date = $yourArray[ 'date' ][ $key ];
    $amount = $yourArray[ 'amount' ][ $key ];

    // execute it!
    $stmt->execute();
}

答案 3 :(得分:0)

function mysql_insert_array($into, $columns, $array){

        $column = explode(",", $columns);

        foreach($column as $c){
            $c = $post[$c];
            $v .= "'$c',";
        }
        $v = trim($v, ",");

        $query = ("INSERT INTO $into($columns) VALUES($v)");
        mysql_query($query);

        return mysql_insert_id();
}

$post["username"] = "Little Bobby Tables";
$post["password"] = "x' OR 1 = 1";

mysql_insert_array("users", "username,password", $post)

编辑:哦,2D数组,不适用。