使用mysql将多行插入数据库

时间:2017-10-18 05:06:09

标签: php mysql sql insert

我的表名:single

id    custmr_id    name      credit     debit      balance
--+-------------+---------+----------+-----------+---------
1      56          ramen      4        0            12(old balance - debit)
2      23          lumen      24       0            35(old balance - debit)
3
4
.
.

我的查询如下:

INSERT INTO `single` (`custmr_id`, `name`, `credit`, `debit`, `balance`) VALUES 
                 ('$custmr_id', '$name', '$credit', '$debit', '$balance')

问题

我想通过php表单添加多个数据。通过上面的查询,我可以添加单行。但是multiple how will I add rows gain and again?如何使用 mysql foreach 查询?

2 个答案:

答案 0 :(得分:1)

您可以像这样创建多个值数组

$custmr_id = $_POST['custmr_id'];
$size = count($custmr_id);
for($i = 0 ; $i < $size ; $i++){
$items[] = array(
    "custmr_id"     => $custmr_id[$i], 
);
}
$values = array();
foreach($items as $item){
    $values[] = "('{$item['custmr_id']}')";
}
$values = implode(", ", $values);

$sql = "INSERT INTO `single` (custmr_id) VALUES  {$values}    ;
" ;
$result = mysql_query($sql);

答案 1 :(得分:0)

步骤I)创建一个这样的数组:

// Render.
render() {

  // Is Authenticated.
  if (this.props.isAuthenticated) return <Redirect to="/authpath"/>

  // Is Not Authenticated.
  // ..

}

步骤II)像这样使用Foreach循环:

$insertArray = array(
                [0] => array(
                    ['custmr_id'] => "1",
                    ['name'] => "Lorem Ipsum",
                    ['credit'] => "10",
                    ['debit'] => "0",
                    ['balance'] => $balance,//Here the caluculation will be done and stored in "$balance" variable.
                ),
                [1] => array(
                    ['custmr_id'] => "2",
                    ['name'] => "Lorem Ipsum",
                    ['credit'] => "20",
                    ['debit'] => "0",
                    ['balance'] => $balance,//Here the caluculation will be done and stored in "$balance" variable.
                )
)

另一种方法

foreach($insertArray as $key => $value){
        INSERT INTO `single` (`custmr_id`, `name`, `credit`, `debit`, `balance`) VALUES ('$value["custmr_id"]', '$value["name"]', '$value["credit"]', '$value["debit"]', '$value["balance"]');
    }