gpt4 book ai didi

java - 将json关联数组插入mysql

转载 作者:行者123 更新时间:2023-11-30 22:24:07 24 4
gpt4 key购买 nike

我一直在寻找如何将多个键-> 值插入到 mysql 数据库中。我可以插入单个对象,但不能插入 foreach 循环中,我一定是做错了什么。考虑到我知道我的 java 代码有效,因此我能够将单个对象存储在数据库的单列表中,这一定是我的 php-syntax 错误 - 即使我遵循了教程。请帮我这是我的 php 代码,它一定有错误

<?php

require_once 'db.php';
$json = file_get_contents('php://input');
$obj = json_decode($json,true);





$st = mysqli_prepare($con, 'INSERT INTO movies(title,year,genre,director) VALUES(?,?,?,?)');

mysqli_stmt_bind_param($st, 'sdss', $title, $year, $genre, $director);


foreach ($obj as $row){
$title = $obj['title'];
$year = $obj['year'];
$genre = $obj['genre'];
$director = $obj['director'];

mysqli_stmt_execute($st);

}


?>

我的 require_once 'db_php';连接到数据库,我从远程 Java 应用程序获取数据。这是我的 javacode - 只是省略了我的数据库 URL 和方法创建

    HttpURLConnection connection= null;
try {

URL obj = new URL(url2);
connection = (HttpURLConnection) obj.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// connection.setRequestProperty("Accept", "application/json");
connection.connect();


OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
JSONObject request = new JSONObject();
request.put("action","login");
request.put("title","The 40 year old virgin");
request.put("year","2004");
request.put("genre","Horror");
request.put("director","Takashi Shimizu");




String output =request.toString();
writer.write(output);
writer.flush();
writer.close();


InputStream input = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;

int responseCode = connection.getResponseCode();
System.out.println("ResponseCode: " + responseCode);


while ((line = reader.readLine()) != null) {
result.append(line);
}

System.out.println("result:" + result.toString());
}


catch (IOException e) {

} finally {

connection.disconnect();

}
}

这是我在 IDE 的控制台中遇到的错误 - eclipse“:警告:mysqli_stmt_bind_param() 期望参数 1 为 mysqli_stmt” 但是,我不知道如何处理它

最佳答案

如果 sql 失败 $st 将不是 mysqli 语句对象,我通常将 mysqli 用作对象并且语句中的任何拼写错误通常显示为在非对象上调用 bind param 的错误,我怀疑你可能有类似的问题。您可以使用类似这样的程序样式来测试错误:

if($st == false){
error_log(mysqli_error($conn));
}

如果准备失败,mysqli_prepare返回false,然后你可以调用mysqli_error传入mysqli_connection来获取最后一个错误的详细信息。

关于java - 将json关联数组插入mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35817766/

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