Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 與 PHP 伺服器交互實例

這個範例完成的功能是:遠端註冊登入之後跳轉到首頁,首頁顯示歡迎訊息,同時把伺服器從資料庫取回的資料以 JSON 格式回傳並呈現在 listview 上。登入部分的寫法參考了一位網友的本地註冊登入實例。

伺服器端 server.php:

<?php
       include('dbconfig.php');

       $address = $_POST['address'];
       $longitude = $_POST['longitude'];
       $latitude = $_POST['latitude'];

       if(empty($address) or empty($longitude) or empty($latitude)){
             die("You have to fill all the fields!");
       }

       $conn = mysql_connect($server,$username,$password);
       if(!$conn){
             die("connection failed:".mysql_error());
       }

       mysql_select_db($dbName,$conn);

       $query = "insert into ".$tableName." values(NULL,'".$address."',".$longitude.",".$latitude.",'".date('Y-m-d H:i:s',time())."');";
       $result = mysql_query($query,$conn);
       if(!$result){
             die("mysql error:".mysql_error());
       }

       echo "add information to database sucessfullly!";
?>

這段伺服器程式先驗證三個欄位是否齊全,再建立連線、選庫,最後組出 insert 敘述寫入並回應結果。若要在正式環境使用,建議把 mysql_* 系列換成 mysqli 或 PDO,並改用參數化查詢以避免 SQL injection。

Copyright © Linux教程網 All Rights Reserved