我一直在尋找如何將多個key-> value插入到mysql數據庫中。 我可以插入單個對象,但不是在foreach循環中,我必須做錯事。考慮到我知道我的java代碼有效,因此我能夠將單個對象存儲在數據庫的單表中,但它必須是我的php語法錯誤 - 即使我遵循教程。請幫我 這裏是我的PHP代碼,其中必須有錯誤將json關聯數組插入到mysql
<?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控制檯得到的錯誤 - 蝕「:警告:mysqli_stmt_bind_param()預計參數1被mysqli_stmt」不過,我不知道如何處理它
嗨蛋車 它解決了我的問題,謝謝! 我得到了一個error_log值爲「1」,我不知道它的含義,但你把我的注意力吸引到了$ st。刪除整數參數「年」,解決了這個問題。我猜想'd'的值是錯誤的。 –
@MartinUtzon我很高興它有幫助。我看到我把$ conn放在我的示例中,但是使用$ con可能會導致奇怪的錯誤日誌輸出,它應該是error_log(mysqli_error($ con));.但無論如何,很高興它幫助你找到問題。 –