2016-04-23 212 views
1

我目前正在使用一個android應用程序,通過PHP從MySQL數據庫中檢索數據,爲此我使用服務但我無法連接到MySQL。 有沒有人對此有過想法或者是否有服務支持?非常感謝。Android服務連接到服務器

public class MyAlarmService extends Service{ 

private NotificationManager mManager; 
public int response = 0; 
@Override 
public IBinder onBind(Intent arg0) 
{ 
    // TODO Auto-generated method stub 
    return null; 
} 
@Override 
public void onCreate() 
{ 
    // TODO Auto-generated method stub 
    super.onCreate(); 
} 

@SuppressWarnings("static-access") 
@Override 
public void onStart(Intent intent, int startId) 
{ 
    super.onStart(intent, startId); 
    makePostRequest(); 
} 

private void makePostRequest() { 


    HttpClient httpClient = new DefaultHttpClient(); 
    // replace with your url 
    HttpPost httpPost = new HttpPost("http://10.0.3.2/folder/detect_h_area.php"); 


    //Post Data 
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3); 
    nameValuePair.add(new BasicNameValuePair("latitued", "34.52234315")); 
    nameValuePair.add(new BasicNameValuePair("longitued", "69.18254074")); 
    nameValuePair.add(new BasicNameValuePair("token", "token123585775")); 

    //Encoding POST data 
    try { 
     httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); 
    } catch (UnsupportedEncodingException e) { 
     // log exception 
     e.printStackTrace(); 
    } 

    //making POST request. 
    try { 
     HttpResponse response = httpClient.execute(httpPost); 
     // write response to log 
     Log.d("Http Post Response:", response.toString()); 
    } catch (ClientProtocolException e) { 
     // Log exception 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // Log exception 
     e.printStackTrace(); 
    } 

} 

@Override 
public void onDestroy() 
{ 
    // TODO Auto-generated method stub 
    super.onDestroy(); 
} 

}

PHP文件

$con = mysql_connect("localhost","root","root"); 
mysql_select_db("test_db"); 

$lat = $_POST['latitued']; 
$lon = $_POST['longitued']; 

if($lat != "" || $lat != "0"){ 
    $lat = substr($lat, 0,5); 
} 
if($lon != "" || $lon != "0"){ 
    $lon = substr($lon, 0,5); 
} 

$result = mysql_query('SELECT count(*) AS total 
         FROM table1 
         WHERE geolat LIKE "%'.$lat.'%" 
         AND geolng LIKE "%'.$lon.'%" 
         GROUP BY '.$lat.' , '.$lon.'' 
        ); 

$row = mysql_fetch_assoc($result); 

if($row['total'] > 0) 
{ 
    echo $row['total'];exit; 
} 
else 
{ 
    echo "null";exit; 
} 

回答

0

有你寫PHP配置MySQL連接?

編輯:

<?php 
$servername = "localhost"; 
$username = "username"; 
$password = "password"; 
// Create connection 
$conn = new mysqli($servername, $username, $password); 
// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 
echo "Connected successfully"; 
?> 
+0

是我寫的PHP文件中查找該 –

+0

你需要配置你的MySQL連接。 –

+0

這裏是鏈接,http://www.w3schools.com/php/php_mysql_connect.asp –