使用PHP从数组插入数据库

时间:2013-10-31 07:46:26

标签: php arrays insert

我有数据库A,包括字段酒店,order_type和description。我想从数组$ new_array中插入数据库A的值。

// array $ new_array

Array
(
[0] => Array
    (
        [order_type] => 1
        [currency] => 26
        [net] => 
        [rate] => 
        [amount] => 
        [bank_surcharge] => 
        [ticket] => 
        [profit] => 
        [selling_price] => 
        [description] => a
        [hotel] => 1
        [vendor] => 11
    )

[1] => Array
    (
        [order_type] => 2
        [currency] => 27
        [net] => 
        [rate] => 
        [amount] => 
        [bank_surcharge] => 
        [ticket] => 
        [profit] => 
        [selling_price] => 
        [description] => b
        [hotel] => 1
        [vendor] => 11
    )
...
...
}

我试过这个剧本但没有发生任何事情:(

for($i = 0; $i < sizeof($new_array['order_type']); $i++){
    mssql_query("INSERT INTO A(hotel_id, order_type,    description) 
    VALUES('$new_array[$i]', '$new_array[$i]', '$new_array[$i]')");
}

如何用PHP做到这一点?请任何人帮助我。

6 个答案:

答案 0 :(得分:3)

尝试传递Connection引用并循环为:

foreach($new_array as $each){
    mssql_query($conn, "INSERT INTO A(hotel_id, order_type, description) 
    VALUES('{$each['hotel']}', '{$each['order_type']}', '{$each['description']}')");
}

答案 1 :(得分:2)

这有帮助吗?

foreach($new_array as $item) {
    mssql_query("INSERT INTO A (hotel_id, order_type, description) 
    VALUES('". $item['hotel'] ."', '". $item['order_type'] ."', '". $item['description']. "')");
}

foreachfor循环非常相似,但它只是迭代所有数组元素。您不需要关心阵列大小。

答案 2 :(得分:2)

1)你的循环无效,应为sizeof($new_array)

2)SQL语句的数组数据访问无效

for($i = 0; $i < sizeof($new_array); $i++){
    mssql_query("INSERT INTO A(hotel_id, order_type, description) VALUES({$new_array[$i]['hotel']}, '{$new_array[$i]['type']}', '{$new_array[$i]['description']}')");
}

答案 3 :(得分:1)

foreach ($new_array as $val){
    mysql_query("INSERT INTO A(order_type, description) VALUES($val['order_type'], $val['description'])");
}

此代码不会插入hotel_id,因为它是表A的主键。

答案 4 :(得分:0)

for ($i = 0; $i < sizeof($new_array['order_type']); $i++) {
    mssql_query("INSERT INTO A(hotel_id, order_type, description) VALUES ('$new_array[$i]["hotel"]', '$new_array[$i]["order_type"]', '$new_array[$i]["description"]')");
}

这应该可行,我猜,虽然没有测试过。

答案 5 :(得分:-1)

试试这个

for($i = 0; $i < sizeof($new_array['order_type']); $i++){
    mssql_query("INSERT INTO A(hotel_id, order_type,    description) 
    VALUES('".$new_array[$i]['hotel']."', '".$new_array[$i]['order_type']."', '".$new_array[$i]['description']."')");
}
相关问题