gpt4 book ai didi

php - 如何在 PHP 中获取 JSON 数组并打印其值?

转载 作者:行者123 更新时间:2023-11-30 21:58:57 25 4
gpt4 key购买 nike

实际上我已经创建了一个包含表行值的数组,我想使用 jQuery 将该数组传递给 PHP 文件,我想将它存储在 MySql 数据库中。

我是这样做的:

var myTableArray = [];

$("table#tbl-nitem tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() {
arrayOfThisRow.push($(this).text());
});

alert(arrayOfThisRow);
arrayOfThisRow.shift();
myTableArray.push(arrayOfThisRow);
}
});
//myTableArray.shift();
alert(myTableArray);

var jsonString = JSON.stringify(myTableArray);
$.ajax({
type: "GET",
url: "script_expenses.php",
data: {
data: jsonString
},
cache: false,

success: function(response) {
if (response == "ok") {
alert("OK");
} else {
alert(response);
}
}
});

上面的代码将创建、存储数组并将其传递给 .php 文件

$conn = require_once 'db_connection.php';
//echo $conn;
session_start();
$data = $_GET['data'];
json_encode($data);

// $sql = "INSERT INTO my_table ( fname, lname ) VALUES ( ?,? )";
//$ins =

$sql = "INSERT INTO expenses_list VALUES (?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($conn, $sql);

foreach($data as $row) {
mysqli_stmt_bind_param('ss', 'TEA');
mysqli_stmt_bind_param('ss', $row['Purpose']);
mysqli_stmt_bind_param('ss', $row['UnitPrice']);
mysqli_stmt_bind_param('ss', $row['Qty']);
mysqli_stmt_bind_param('ss', $row['DTime']);
mysqli_stmt_bind_param('ss', $row['Description']);
$result = mysqli_stmt_execute($stmt);
}

flush();

上面的代码将接收数组并尝试存储在数据库中。但是我在 foreach 语句中收到一个错误:为每个提供的参数无效

查了下才知道接收的值不是数组。如何解决问题???

最佳答案

就这样

$data = $_GET['data'];

$data = json_decode($data,true);

现在您可以在 foreach 循环中使用 $data更新 1

$conn =  require_once'db_connection.php';
session_start();
$data = $_GET['data'];
$data = json_decode($data,true);

$sql = "INSERT INTO expenses_list VALUES (?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($conn,$sql);

foreach($data as $row){
mysqli_stmt_bind_param('s', 'TEA');
mysqli_stmt_bind_param('s', $row['Purpose']);

//mysqli_stmt_bind_param('s', $row['UnitPrice']);
//if UnitPrice is double values then use
mysqli_stmt_bind_param('d', $row['UnitPrice']);

//mysqli_stmt_bind_param('s', $row['Qty']);
//if Qty is integer then use
mysqli_stmt_bind_param('i', $row['Qty']);
mysqli_stmt_bind_param('s', $row['DTime']);
mysqli_stmt_bind_param('s', $row['Description']);
$result = mysqli_stmt_execute($stmt);
}

在mysqli_stmt_bind_param中请使用以下类型

i对应的变量类型为整型

d对应的变量是double类型

对应的变量的类型是string

b对应的变量是一个blob,会打包发送

如需更多引用,请查看此 http://php.net/manual/en/mysqli-stmt.bind-param.php

关于php - 如何在 PHP 中获取 JSON 数组并打印其值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com