[英]Why can't I set the values for the POST variables?
我目前正在開發一個與服務器(目前為本地)交互的Android應用。 為此,我使用PHP與服務器通信Java代碼。 這是我第一次使用PHP,因此我很難過。
由於某些原因,我需要保存在數據庫中的所有值都為null,因此當我測試PHP代碼時是從應用程序還是從URL獲取它們都沒有關系。 我收到的唯一消息是:
{“成功”:0,“消息”:“缺少必填字段”}。
我嘗試了print_r($ _POST),但得到了:Array(),不知道那是什么意思。 我也嘗試了在互聯網上看到的所有內容,但均未成功。
這是PHP代碼:
<?php
$response = array();
if (!empty($_POST['name']) && !empty($_POST['breed']) && !empty($_POST['type']) && !empty($_POST['description']) && !empty($_POST['images']) && !empty($_POST['coords'])) {
$name = $_POST['name'];
$breed = $_POST['breed'];
$type = $_POST['type'];
$description = $_POST['description'];
$images = $_POST['images'];
$coords = $_POST['coords'];
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = "INSERT INTO lost_pets (name, breed, type, description, images, coords) VALUES(':name', ':breed', ':type', ':description', ':images', ':coords')";
$stmt = $db->prepare($result);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':breed', $_POST['breed'], PDO::PARAM_STR);
$stmt->bindParam(':type', $_POST['type'], PDO::PARAM_STR);
$stmt->bindParam(':description', $_POST['description'], PDO::PARAM_STR);
$stmt->bindParam(':images', $_POST['images'], PDO::PARAM_STR);
$stmt->bindParam(':coords', $_POST['coords'], PDO::PARAM_STR);
$stmt->execute();
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
?>
我很確定問題出在此代碼中,而不是Java代碼中。 希望您能在這里幫助我,謝謝!
您正在錯誤地將SQL查詢字符串分配給$result
變量,然后巧妙地測試查詢字符串本身是否成功。
使用$query
作為查詢字符串,並測試$stmt->execute()
是否失敗:
if ($stmt->execute() === FALSE) {
// ERROR
}
else {
// Success!
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.