开发者

How to post an array to MySQL

How can we post following array to mysql(columns: id, date, amount)...

Array
(
   [date] => Array
   (
      [0] => 03/27/2011
      [1] => 04/27/2011
    )
   [amount] => Array
   (
   开发者_开发问答   [0] => 5000
      [1] => 5000
    )
)

How can we get data(dates and amounts) from this array to post intomysql using foreach?

we are getting this array using following fields 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][]" />

thanks for your support.


Loop over the first subarray, and keep the $i index to access the second alike:

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

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


Try this:

<?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));


Here's a mysqli version (untested, and I never use mysqli, but should work I believe)

// 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();
}


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)

edit: Oh, 2D array, doesn't work with that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜