2017-08-05 80 views
0

我目前正在開發一個與服務器交互的Android應用程序(現在爲Local)。 爲此,我使用PHP將Java代碼與服務器進行通信。 這是我第一次使用PHP,所以我很難與此。爲什麼我不能設置POST變量的值?

由於某些原因,我需要保存在數據庫中的所有值都是空的,如果我從應用程序或URL中獲取它們並不重要,那麼當我測試PHP代碼時。我得到的唯一消息是:

{「success」:0,「message」:「必填字段丟失」}。

我試着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代碼。我希望你能幫助我,謝謝!

+0

嘗試得到的錯誤,並張貼在這裏。 –

+1

您可以使用郵遞員來檢查服務器響應是否正確 –

+1

'我試過print_r($ _POST),我得到:Array(),不知道這意味着什麼。這意味着$ _POST數組是空的。 – Spectarion

回答

1

您錯誤地將您的SQL查詢字符串分配給$result變量,然後愉快地測試查詢字符串本身以獲得成功。

使用$query爲您的查詢字符串,並測試$stmt->execute()失敗,而不是:

if ($stmt->execute() === FALSE) { 
    // ERROR 
} 
else { 
    // Success! 
} 
+0

現在,我得到這個:調用未定義的方法DB_CONNECT ::準備() –

+0

我發現了錯誤,我忘了實例化DB_CONNECT內的連接方法,它返回了連接。你的代碼工作完美。非常非常感謝你! –

相關問題