为什么我不能设置POST变量的值?

为什么我不能设置POST变量的值?

问题描述:

我目前正在开发一个与服务器交互的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

您错误地将您的SQL查询字符串分配给$result变量,然后愉快地测试查询字符串本身以获得成功。

使用$query为您的查询字符串,并测试$stmt->execute()失败,而不是:

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

现在,我得到这个:调用未定义的方法DB_CONNECT ::准备() –

+0

我发现了错误,我忘了实例化DB_CONNECT内的连接方法,它返回了连接。你的代码工作完美。非常非常感谢你! –