2012-04-09 71 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: *');