【发布时间】:2018-03-22 00:26:27
【问题描述】:
我需要帮助来理解这个聪明的 PHP Multiple Mysql Insert 代码。
请允许我强调一下,我在网上找到了对 JSON 数据的解析,剩下的就是我的了。
完美无瑕,但有些事情我并不完全理解......
如何构建插入字符串?如果你能评论代码,那就太好了……
是重复插入还是一个巨大的插入PDO执行?
我注意到它使用的是 bindValue 而不是 bindParameter。这是因为这个动态 PHP 脚本的性质吗?
可选:如果您知道一种简单明了的方法来执行此操作,请务必让我知道您是否有机会。
JSON POST 数据
[
{
"PK_LINE_ITEM_ID":555,
"DESCRIPTION":"LINE ITEM 5",
"QUANTITY":0,
"UNIT":"SF",
"COST":0,
"TOTAL":"0.00"
},
{
"PK_LINE_ITEM_ID":777,
"DESCRIPTION":"LINE ITEM 7",
"QUANTITY":0,
"UNIT":"SF",
"COST":0,
"TOTAL":"0.00"
},
{
"PK_LINE_ITEM_ID":999,
"DESCRIPTION":"LINE ITEM 9",
"QUANTITY":0,
"UNIT":"SF",
"COST":0,
"TOTAL":"0.00"
}
]
PHP 脚本 (data_post_json_insert_all.php)
<?php
/* Status Codes
return 0 = Nothing to Update (n/a)
return 1 = Successful Insert Query
return 2 = Database Connection refused
return 3 = MySQL Query Error OR Wrong URL Parameters */
/* Disable Warnings so that we can return ONLY what we want through echo. */
mysqli_report(MYSQLI_REPORT_STRICT);
// First get raw POST input
$raw_post = file_get_contents('php://input');
// Run through url_decode..
$url_decoded = urldecode($raw_post);
// Run through json_decode...
// false to allow for reference to oject. eg. $column->name instead of $column["name"] in the foreach.
$json_decoded = json_decode($url_decoded, true);
$table_name = 'tbl_xyz';
// INCLUDE DB CONNECTION STRING
include 'php_pdo_mysql_connect.php';
pdoMultiInsert($table_name, $json_decoded, $link);
function pdoMultiInsert($mysql_table, $json_decoded, $pdo_object) {
//Will contain SQL snippets.
$rows_sql = [];
//Will contain the values that we need to bind.
$to_bind = [];
//Get a list of column names to use in the SQL statement.
$column_names = array_keys($json_decoded[0]);
//Loop through our $json_decoded array.
// begin outter for each
foreach($json_decoded as $array_index => $row) {
$params = [];
// begin inner for each --------------------------------
foreach($row as $column_name => $column_value) {
$param = ":" . $column_name . $array_index;
$params[] = $param;
$to_bind[$param] = $column_value;
} // end inner for each --------------------------------
$rows_sql[] = "(" . implode(", ", $params) . ")";
} // end outter for each
//Construct our SQL statement
$sql = "INSERT INTO `$mysql_table` (" . implode(", ", $column_names) . ") VALUES " . implode(", ", $rows_sql);
//Prepare our PDO statement.
$pdo_statement = $pdo_object->prepare($sql);
//Bind our values.
foreach($to_bind as $param => $val) {
$pdo_statement->bindValue($param, $val);
}
//Execute our statement (i.e. insert the json_decoded data).
return $pdo_statement->execute();
}
$link = null;
$stmt = null;
// return 1 = Successful Insert Query
echo '1';
谢谢
【问题讨论】:
-
您可以只打印
$sql——这是一个插入多行的语句。代码已经注释并且非常清晰。不过我修好了你的标签。 -
对我来说不是。如此多地使用数组......分配......从哪里到哪里?内爆……爆炸……叹息……
-
我最终会明白的。在这里试一试。