2016-12-02 103 views
1

我已經建立了一個php文件來根據發送郵件的內容來更改查詢,我已經使用表單測試了它併成功運行。React Native Fetch:發送郵件但未在PHP文件中收到

<?php 

$pdo = new PDO("mysql:host=localhost;dbname=...","...","...",array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); 
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

if(isset($_POST['country'])){ 

    $query = stripslashes("SELECT A.id, A.supplier_id, A.pickup_date, A.dropoff_date, A.rate, A.days_allowed, A.fuel_allowed, A.location_from, A.location_to, A.dropoff_office_id,  A.pickup_office_id, A.vehicle_type_id, B.city AS location_from_city, C.city AS location_to_city, D.vehicle_type,D.transmission FROM _relocation_deals A JOIN _airport_codes_lookup B ON A.location_from = B.code JOIN _airport_codes_lookup C ON A.location_to = C.code JOIN _vehicle_types D ON A.vehicle_type_id = D.id WHERE B.country = '".$_POST['country']."' AND A.active = 1 AND A.status = 1 ORDER BY A.pickup_date ASC"); 

$data = array(); 

try 
{ 
    $sql = $query; 
    $result = array(); 
    $stmt = $pdo->prepare($sql); 
     $stmt->execute(); 
    while($result = $stmt->fetch()){ 
     $data[] = $result; 
    } 
} 
    catch (PDOException $e) 
{ 
    echo $e->getMessage(); 
} 

    echo json_encode($data); 
}else{ 
    $arr = array('error' => 'no post sent'); 
    echo json_encode($arr); 
} 

?> 

我正在使用fetch在反應本機中發佈到此文件。

fetch(REQUEST_URL, { 
    method: 'POST', 
    headers: { 
    'Accept': 'text/html', 
    'Content-Type': 'application/x-www-form-urlencoded' 
    }, 
    body: JSON.stringify({ 
    country: "New Zealand" 
    }) 
}) 
    .then((response) => response.json()) 
    .then((responseData) => { 
    console.log(responseData); 
    }) 
    .catch((error) => { 
    console.error(error); 
}); 

我可以在我的網絡檢查員看到發送的數據爲{「國」,「新西蘭」}但我得到{「錯誤」,「無後發送」}的響應。是否有我的PHP文檔沒有收到這篇文章的原因?謝謝。

回答

0

你需要編碼請求體as URI而不是JSON的:

body: 'country=' + encodeURIComponent('New Zealand'), 

或者你也可以從php://input讀取POST參數和JSON手動進行譯碼。

此外,您的PHP代碼是非常vulnerable。您絕對不應該在SQL查詢字符串中插入來自HTTP請求和其他不可信數據的參數。 stripslashes()不是一種轉義SQL特殊字符的方法。您已經使用PDO並準備了語句,因此只需通過適當的方法(如bindValue())綁定參數即可。