html post mysql,Inserting HTML Form $_POST Array Into MySQL Using Implode

问题

I have the following html submit form. This form is a PHP_SELF and stores the input data as an array in $_POST.

Direct Bill Information:

DB #: DB Amount:

DB #: DB Amount:

DB #: DB Amount:

DB #: DB Amount:

DB #: DB Amount:

DB #: DB Amount:

DB #: DB Amount:

DB #: DB Amount:

DB #: DB Amount:

DB #: DB Amount:

I have a MySQL table that has the fields 'db_num' and 'db_amnt', and I want to insert all the input data in the array into the table. I've looked around and 'implode' seems to be the best way, but after much research I still can't get it to work. The entire PHP executes and finishes without error, however, instead of displaying all 10 rows of both columns, it just displays 2 rows of the two columns with values = 0 for all entries. This is the code I'm using:

$sql2 = array();

foreach($_POST as key=>$value)

{

if(key != 'submit')

{

if($value != '')

{

$sql2[] = '("'.mysql_real_escape_string($value['db_num']).'", "'.$value['db_amnt'].'")';

}

}

}

mysql_query('INSERT INTO ' .$tablename_db. '(db_num, db_amnt) VALUES '.implode(',', $sql2));

I did a little debugging and echoed the $value in the foreach loop, and it turns out that it's only displaying three terms; 'Array', 'Array', and 'submit'. Further checks showed that the only way I can get the values from the submit form to show is if I do a foreach loop through $_POST[db_num] and $_POST[db_amnt] instead of just $_POST. I'm not really sure why it's doing this and how to fix it. This is my first code in PHP and I'm learning as I go. I really appreciate any help that I can get!

回答1:

try this

$db_num = $_POST['db_num'];

$db_amnt = $_POST['db_amnt'];

$items = array_combine($db_num,$db_amnt);

$pairs = array();

foreach($items as $key=>$value){

$pairs[] = '('.intval($key).','.intval($value).')';

}

mysql_query('INSERT INTO ' .$tablename_db. '(db_num, db_amnt) VALUES '.implode(',',$pairs));

回答2:

Upon submit, your html form will be generating the following $_POST array (I'll fabricate some sample values).

$_POST = [

'db_num' => ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],

'db_amnt' => ['100', '125', '150', '175', '200', '225', '250', '275', '300', '325']

];

In other words, $_POST['db_num'] will have $_POST['db_num'][0] holding 1 all the way through $_POST['db_num'][9] holding 10. Likewise, $_POST['db_amnt'][0] will hold 100, $_POST['db_amnt'][1] will hold 125, and so forth. Even if a user fails to fill in one of the fields, the empty field will still be submitted and the value will be a zero-width string (empty string).

You have done yourself a great service by structuring your form data to provide such a clean and instantly usable/traversable set of data.

There is no need to restructuring the incoming data (despite voodoo's suggestion to use array_combine()). If any extra effort is called for at all, you might want to validate the "paired" values from each row of the form. For instance, I assume that you will only want to store data if both db_num and db_amnt for a given row are non-empty -- so I'll build that check into my suggested snippet.

$conn = new mysqli($server, $user, $password, $database);

$stmt = $conn->prepare("INSERT INTO {$tablename_db} (db_num, db_amnt) VALUES (?,?)");

$stmt->bind_param("ii", $num, $amnt); // name the two variables which will pass integer values where the ?'s are located

foreach ($_POST['db_num'] as $index => $num) {

$amnt = $_POST['db_amnt'][$index];

if (strlen($num) && strlen($amnt)) {

$stmt->execute(); // only INSERT qualifying rows

}

}

Note, that if your db_amnt values have decimal places (they are floating point numbers), then you can change the i in the bind_param() call to d. Some people prefer the simplest route of declaring all of the values as s (string), but I like to rein it in when dealing with predictable user input.

Here is a demonstration of the iterating technique.

If you have other validating checks to make, just add them to my if expression.

If you want enjoy individual success checking, you can write something immediately under execute() to reference the affected rows.

Re-using a prepared statement is one of two ways that this process should be done with mysqli. The other involves building one, all-encompassing INSERT query with all rows in it, but that involves a bit more preparation. These two mysqli techniques are injection safe, stable, and efficient.

Finally, some developers will say that you should be checking if each index actually does exist in the subarrays before trying to access them; other developers insist that it is not necessary to handle Notices that are generated by users which are deliberately hacking your html. I'll leave it to individual researchers to determine whether they wish to make isset() calls before and while iterating.

来源:https://stackoverflow.com/questions/11720981/inserting-html-form-post-array-into-mysql-using-implode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值