本文目錄一覽:
- 1、怎麼連接android和php mysql資料庫
- 2、android與php交互的問題
- 3、android 怎麼訪問php路徑並 獲取數據
- 4、如何連接android和php mysql資料庫
- 5、Android怎麼調用php寫的網路介面
怎麼連接android和php mysql資料庫
如何連接android和php mysql資料庫
我們先來看一個簡單的Android app例子(這裡是一個商品存貨清單項目),在Android程序中,我們可以訪問(call)PHP腳本來執行簡單的CRUD操作(創建,讀取,更新,刪除)。為了使你對它的體系結構有一個大概的了解,這裡先說一下它是怎麼工作的。首先你的Android項目訪問(call)PHP腳本來執行一條數據操作,我們稱它為「創建」。然後PHP腳本連接MySQL資料庫來執行這個操作。這樣,數據從Android程序流向PHP腳本,最終存儲在MySQL資料庫中。
好了,讓我們來深入的看一下。
請注意:這裡提供的代碼只是為了使你能簡單的連接Android項目和PHP,MySQL。你不能把它作為一個標準或者安全編程實踐。在生產環境中,理想情況下你需要避免使用任何可能造成潛在注入漏洞的代碼(比如MYSQL注入)。MYSQL注入是一個很大的話題,不可能用單獨的一篇文章來說清楚,並且它也不在本文討論的範圍內,所以本文不以討論。
1. 什麼是WAMP Server
WAMP是Windows,Apache,MySQL和PHP,Perl,Python的簡稱。WAMP是一個一鍵安裝的軟體,它為開發PHP,MySQL Web應用程序提供一個環境。安裝這款軟體你相當於安裝了Apache,MySQL和PHP。或者,你也可以使用XAMP。
2. 安裝和使用WAMP Server
你可以從下載WAMP,安裝完成之後,可以從開始-所有程序-WampServer-StartWampServer運行該程序。
在瀏覽器中輸入來測試你的伺服器是否安裝成功。同樣的,也可以打開來檢驗phpmyadmin是否安裝成功。
3. 創建和運行PHP項目
現在,你已經有一個能開發PHP和MYSQL項目的環境了。打開安裝WAMP Server的文件夾(在我的電腦中,是C:\wamp\),打開www文件夾,為你的項目創建一個新的文件夾。你必須把項目中所有的文件放到這個文件夾中。
新建一個名為android_connect的文件夾,並新建一個php文件,命名為test.php,嘗試輸入一些簡單的php代碼(如下所示)。輸入下面的代碼後,打開,你會在瀏覽器中看到「Welcome,I am connecting Android to PHP,MySQL」(如果沒有正確輸入,請檢查WAMP配置是否正確)
test.php
4. 打開MainScreenActivity.java為main_screen.xml文件里的兩個按鈕添加點擊事件
MainScreenActivity.java
7. 添加一個新產品(寫入)
創建一個新的view和activity來向MySQL資料庫添加新產品。
新建一個簡單的表單,創建提供輸入產品名稱,價格和描述的EditText
add_product.xml
8. 新建一個Activity來處理向MySQL資料庫插入新產品。
新建名為NewProductActivity.java的文件,輸入以下代碼。在下面的代碼中
首先,從EditText獲得用戶輸入的產品數據,格式化成基本參數格式
然後,向create_product.php發送請求,通過HTTP POST創建一個新的產品
最後,從create_product.php獲取json返回值,如果success值為1,新得到的列表中就加入了新增的產品。
NewProductActivity.java
11. JSONParser類
我用一個JSONParser類從URL獲得JSON格式的數據。這個類支持兩種http請求,GET和POST方法從URL獲取JSON數據
JSONParser.java
packagecom.example.androidhive; importjava.io.BufferedReader; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.io.UnsupportedEncodingException; importjava.util.List; importorg.apache.http.HttpEntity; importorg.apache.http.HttpResponse; importorg.apache.http.NameValuePair; importorg.apache.http.client.ClientProtocolException; importorg.apache.http.client.entity.UrlEncodedFormEntity; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.client.utils.URLEncodedUtils; importorg.apache.http.impl.client.DefaultHttpClient; importorg.json.JSONException; importorg.json.JSONObject; importandroid.util.Log; publicclassJSONParser { staticInputStream is = null; staticJSONObject jObj = null; staticString json = “”; // constructor publicJSONParser() { } // function get json from url // by making HTTP POST or GET mehtod publicJSONObject makeHttpRequest(String url, String method, ListNameValuePair params) { // Making HTTP request try{ // check for request method if(method == “POST”){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = newDefaultHttpClient(); HttpPost httpPost = newHttpPost(url); httpPost.setEntity(newUrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }elseif(method == “GET”){ // request method is GET DefaultHttpClient httpClient = newDefaultHttpClient(); String paramString = URLEncodedUtils.format(params, “utf-8”); url += “?”+ paramString; HttpGet httpGet = newHttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch(UnsupportedEncodingException e) { e.printStackTrace(); } catch(ClientProtocolException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } try{ BufferedReader reader = newBufferedReader(newInputStreamReader( is, “iso-8859-1”), 8); StringBuilder sb = newStringBuilder(); String line = null; while((line = reader.readLine()) != null) { sb.append(line + “\n”); } is.close(); json = sb.toString(); } catch(Exception e) { Log.e(“Buffer Error”, “Error converting result “+ e.toString()); } // try parse the string to a JSON object try{ jObj = newJSONObject(json); } catch(JSONException e) { Log.e(“JSON Parser”, “Error parsing data “+ e.toString()); } // return JSON String returnjObj; } }
到這裡,本教程就結束了。
android與php交互的問題
1 加入許可權:
uses-permission android:name=”android.permission.INTERNET” /
uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” /
2、啟動一個新線程
android4.0開始不允許直接在ui線程直接操作httpClient
3 、注意url:
(不要填寫:127.0.0.1 這個是本機電腦的,模擬器有自己的默認ip)
4、通過handler將數據從新線程中傳送出來
步驟:
1 創建一個httpClient 對象
2 使用post發送數據 創建一個HttpPost對象
3 設置請求參數用setEntity()
4 調用httpClient對象的execute() 發送請求,返回一個HttpResponse
5 調用HttpResponse的getEntity() 方法可以獲取HttpEntity 對象
android 怎麼訪問php路徑並 獲取數據
從php端獲得的數據如何展示由你需求決定,比如是一個條數據,你可以用TextView顯示;如果是數據集列表,你可以用ListView顯示。測試發送的請求,你可以在php端用var_export($_REQUEST);輸出請求到一個log日誌文件查看。
如何連接android和php mysql資料庫
使用JSON連接Android和PHP Mysql資料庫方法:
1、打開安裝WAMP Server的文件夾,打開www文件夾,為你的項目創建一個新的文件夾。必須把項目中所有的文件放到這個文件夾中。
2、新建一個名為android_connect的文件夾,並新建一個php文件,命名為test.php,嘗試輸入一些簡單的php代碼(如下所示)。
test.php
?php
echo”Welcome, I am connecting Android to PHP, MySQL”;
?
3、創建MySQL資料庫和表
創建了一個簡單的只有一張表的資料庫。用這個表來執行一些示例操作。現在,請在瀏覽器中輸入,並打開phpmyadmin。你可以用PhpMyAdmin工具創建資料庫和表。
創建資料庫和表:資料庫名:androidhive,表:product
CREATE TABLE products(
pid int(11) primary key auto_increment,
name varchar(100) not null,
price decimal(10,2) not null,
description text,
created_at timestamp default now(),
updated_at timestamp
);
4、用PHP連接MySQL資料庫
現在,真正的伺服器端編程開始了。新建一個PHP類來連接MYSQL資料庫。這個類的主要功能是打開資料庫連接和在不需要時關閉資料庫連接。
新建兩個文件db_config.php,db_connect.php
db_config.php——–存儲資料庫連接變數
db_connect.php——-連接資料庫的類文件
db_config.php
?php
/*
* All database connection variables
*/
define(‘DB_USER’, “root”); // db user
define(‘DB_PASSWORD’, “”); // db password (mention your db password here)
define(‘DB_DATABASE’, “androidhive”); // database name
define(‘DB_SERVER’, “localhost”); // db server
?
5、在PHP項目中新建一個php文件,命名為create_product.php,並輸入以下代碼。該文件主要實現在products表中插入一個新的產品。
?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST[‘name’]) isset($_POST[‘price’]) isset($_POST[‘description’])) {
$name = $_POST[‘name’];
$price = $_POST[‘price’];
$description = $_POST[‘description’];
// include db connect class
require_once __DIR__ . ‘/db_connect.php’;
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query(“INSERT INTO products(name, price, description) VALUES(‘$name’, ‘$price’, ‘$description’)”);
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response[“success”] = 1;
$response[“message”] = “Product successfully created.”;
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response[“success”] = 0;
$response[“message”] = “Oops! An error occurred.”;
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response[“success”] = 0;
$response[“message”] = “Required field(s) is missing”;
// echoing JSON response
echo json_encode($response);
}
?
JSON的返回值會是:
當POST 參數丟失
[php] view plaincopy
{
“success”: 0,
“message”: “Required field(s) is missing”
}
Android怎麼調用php寫的網路介面
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(“?”+ “tel=” + tel);
HttpResponse response = httpclient.execute(httpget);
相應的api.php:
$tel= $_GET[‘tel’];
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/191955.html