2012-04-09 80 views
0

我是新來的PHP編程,並有關於它的知識貧乏,但我想用它來使Web服務我的客戶端Android應用程序......PHP的Web服務與Android

我開始製作我的第一個Web服務使用PHP和它的工作很好,但我想知道我怎麼可以讓一個文件有我所有的函數和方法,我需要以及如何將其從Android的

調用

謝謝

這是的functions.php

<?php 
    function GetAllRest() 
    { 
    mysql_connect("localhost","root","root"); 
    mysql_select_db("myhoteldb"); 
    $sql=mysql_query("SELECT rest_id ,rest_name,cuisine,no_tables,bg_img,rest_logo  FROM restaurant"); 
    while($row=mysql_fetch_assoc($sql)) 
    $output[]=$row; 
    print(json_encode($output)); 
    mysql_close(); 
} 
function GetAllCategory($lang_id,$rest_id) 
{ 
    mysql_connect("localhost","root","root"); 
    mysql_select_db("myhoteldb"); 
    $sql=mysql_query("SELECT cat_lang.rowid ,cat_lang.cat_id as _id,lang_id, cat_name,cat_description from cat_lang ,menu_category WHERE lang_id= $lang_id AND restaurant= $rest_id "); 

     while($row=mysql_fetch_assoc($sql)) 
    $output[]=$row; 
    print(json_encode($output)); 
     mysql_close(); 

    } 



    ?> 

和URL http://localhost/mywebservices.php?op=GetAllCategory&lang_id=1&rest_id=1

,我得到這個錯誤現在

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in  

C:\ XAMPP \ htdocs中\ functions.php的第22行

Notice: Undefined variable: output in C:\xampp\htdocs\functions.php on line 24 
    null 
+0

可能重複的[警告:mysql_fetch_ *期望參數1是資源,布爾給定錯誤](http://stackoverflow.com/questions/11674312/warning-mysql-fetch-expects-parameter-1-to-be-resource-boolean -given-error) – j0k 2012-07-29 07:28:32

回答

1

作爲一種理念,我d建議包括想要在你的url中運行的函數名稱。 然後,獲取函數名和參數,它們傳遞到PHP的

call_user_func_array() 

功能。

這裏是一個功能處理的一個非常基本的思路:

您要求的網址應該是這樣的:

http://www.mysite.com/webservice.php?op=CallFunctionOne&param_a=test&param_b=test2 

這裏是處理路由呼叫轉接到您的功能:

require_once("./functions.php"); 

if(!empty($_SERVER["QUERY_STRING"])){ 
    $query_str = stripslashes($_SERVER['QUERY_STRING']); 
    parse_str($query_str,$args); 
    $op = array_shift($args); 
    if(is_callable ($op)){ 
     call_user_func_array($op,$args); 
    } 
    else{ 
     echo "Handler error.<br />"; 
     echo $op . " function is not callable."; 
    } 
} 

而functions.php文件將包括你的功能。 希望它會給出一些想法。

+0

你能解釋一下嗎?總的例子,因爲我告訴你,我對php – Basant 2012-04-09 07:52:44

+0

知之甚少,如果我有沒有使用參數的函數,它會是 – Basant 2012-04-09 08:01:50

+0

,你可以傳遞一個空數組。如果我解釋更多,基本上我展示的是基於URL的簡單調用處理程序。 「op」是你想從android應用程序中調用的函數名稱。一旦你提出請求,你的php應用程序將解析url並獲取函數名稱。基於函數名稱,它會回調該函數,該函數將位於您的functions.php文件中。 – selo 2012-04-09 08:08:33

1

如果你知道PHP,那麼我假設你會知道HTML。

PhoneGap允許您使用HTML,Javascript和CSS在andriod上運行應用程序。 http://phonegap.com/start

使用Javascript,您可以向您的web php文件發出頁面請求。

這裏是一個jQuery例如

<script> 
$.ajax({ 
    url: 'http://example.com/myfile.php', 
    dataType: 'json', 
    success: function(data) { 
    alert(data.rest_name); // do whatever you want with the json response 
    } 
}); 
</script> 

爲了使您需要添加到PHP文件頭這個跨域(不確定的,如果應用程序需要跨域驗證壽)

header('Access-Control-Allow-Origin: *');