如何在Android中使用PHP脚本来获得MySQL数据库值 [英] How to get values from mysql database using php script in android

查看:193
本文介绍了如何在Android中使用PHP脚本来获得MySQL数据库值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法获取从MySQL数据库中的数据。我maked一个Android应用程序,它连接到MySQL数据库并获取使用PHP脚本的数据....
当我运行code将其抛出异常的字符串不能转换为jsonarray ....
还指导我在哪里,我把我的PHP脚本XAMP
PHP脚本:

  $ CON = mysql_connect(localhost的根,);
 如果(!$ CON)
 {
   死亡(无法连接:'mysql_error());
 }
 mysql_select_db(登录,$ CON);
 $ SQL =的mysql_query(SELECT * FROM类别ORDER BY`category`.`category` ASC);
 而($行= mysql_fetch_assoc($ SQL))
 $输出[] = $行;
  打印(json_en code($输出));
  mysql_close($ CON);

code: -

 电视=(的TextView)findViewById(R.id.textView1);
    字符串结果= NULL;
    InputStream为= NULL;
    StringBuilder的SB = NULL;
    ArrayList的namevaluepairs中=新的ArrayList();
    列表R =新的ArrayList();
    尝试{
    // HTTP POST
    HttpClient的HttpClient的=新DefaultHttpClient();
    HttpPost httppost =新HttpPost(HTTP://ip../xampp/htdocs/db.php);
    httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
    HTT presponse响应= httpclient.execute(httppost);
    HttpEntity实体= response.getEntity();
    是= entity.getContent();
    }
    赶上(例外五){
    Toast.makeText(getBaseContext(),e.​​toString(),Toast.LENGTH_LONG).show();
    }
    //响应转换成字符串
    尝试
    {
    读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是,UTF-8));
    SB =新的StringBuilder();
    串线= NULL;
    而((行= reader.readLine())!= NULL)
    {
    sb.append(行+\\ n);
    }
    is.close();
    结果= sb.toString();
    }
    赶上(例外五)
    {
    Toast.makeText(getBaseContext(),e.​​toString(),Toast.LENGTH_LONG).show();
    }
    // END响应转换成字符串
    尝试{
    JSONArray jArray =新JSONArray(结果);
    JSONObject的json_data = NULL;
    的for(int i = 0; I< jArray.length();我++){
    json_data = jArray.getJSONObject(ⅰ);
    tv.append(json_data.getString(类)的toString()+\\ n);
    }    }
    赶上(JSONException E1){
    Toast.makeText(getBaseContext(),e1.toString(),Toast.LENGTH_LONG).show();
    }赶上(ParseException的E1){
    Toast.makeText(getBaseContext(),e1.toString(),Toast.LENGTH_LONG).show();
    }


解决方案

通过PHP到Android从MySQL取值方法如下:

假设你有一个登录活动

用户输入用户名和密码。现在赶上价值和发送到PHP脚本。
Android的code,因为这是如下:

  btnlogin.setOnClickListener(新View.OnClickListener()
        {
                公共无效的onClick(视图v)
            {                        。UNAME = username.getText()的toString();
                        upass = password.getText()的toString()。
                        HttpClient的客户端=新DefaultHttpClient();                        透射电镜=htt​​p://10.0.2.2:80/verify-login.php?username=+ +的uname与&密码=+ upass;
                        HTTPGET请求=新HTTPGET(TEM);
                        尝试
                        {
                            HTT presponse响应= client.execute(请求);
                            HttpEntity实体= response.getEntity();
                            InputStream为= entity.getContent();
                            InputStreamReader的ISR =新的InputStreamReader(是);
                            读者的BufferedReader =新的BufferedReader(ISR);
                            结果= reader.readLine();
                        }                        赶上(例外五)
                        {
                            e.printStackTrace();
                        }                        如果(result.equals(0)==真)
                        {
                            Toast.makeText(getApplicationContext(),对不起再试,1500).show();                        }
                        其他
                        {
                            Toast.makeText(getApplicationContext(),欢迎客户,1500).show();
                            myIntent =新意图(login_page.this,Welcome_page.class);                        }
                    }        });

在PHP脚本的一面。在code,从数据库中提取值并返回到Android是如下:

 < PHP    mysql_connect(localhost的根,)或死亡(mysql_error());
    mysql_select_db(登录)或死亡(mysql_error());    $用户名= $ _ REQUEST [用户名];
    $密码= $ _ REQUEST ['密码'];
    $ SelectQuery =SELECT * FROM EmpLogin那里C_Username ='$用户名和C_Password ='​​$的密码';
    $结果= mysql_query($ SelectQuery)或死亡(mysql_error());    $数= mysql_num_rows($结果);
    $行= mysql_fetch_array($结果);
    如果($计数== 0)
        回声0;
    其他
        回声$行['C_ID'];
?>

这样,您就可以获取从DB值,并发送回机器人。希望这可以帮助你。
如果您有任何疑问,那么就随时问我。

i can not fetch data from mysql database. i maked an android app which connect to mysql db and fetch data using php script.... when i run code it throws exception string cannot convert to jsonarray.... Also guide me where i put my php script in XAMP PHP script:

$con = mysql_connect("localhost","root","");
 if (!$con)
 {
   die('Could not connect: ' . mysql_error());
 }
 mysql_select_db("login",$con);
 $sql=mysql_query("SELECT * FROM category ORDER BY `category`.`category` ASC");
 while($row=mysql_fetch_assoc($sql))
 $output[]=$row;
  print(json_encode($output));
  mysql_close($con);

Code:-

tv=(TextView)findViewById(R.id.textView1);
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    ArrayList nameValuePairs = new ArrayList();
    List r = new ArrayList();
    try{
    //http post
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://ip../xampp/htdocs/db.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    }
    catch(Exception e){
    Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
    }
    //Convert response to string
    try
    {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
    sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null)
    {
    sb.append(line +"\n");
    }
    is.close();
    result = sb.toString();
    }
    catch(Exception e)
    {
    Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
    }
    //END Convert response to string
    try{
    JSONArray jArray = new JSONArray(result);
    JSONObject json_data=null;
    for(int i=0;i<jArray.length();i++) {
    json_data = jArray.getJSONObject(i);
    tv.append(json_data.getString("category").toString()+"\n");
    }

    }
    catch(JSONException e1){
    Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
    } catch (ParseException e1) {
    Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
    }

解决方案

The method to fetch value from mysql through php to android is as below:

Suppose you have a login Activity

User enter Username and Password. now catch both value and send to php script. the android code for it is as below:

btnlogin.setOnClickListener(new View.OnClickListener()
        {
                public void onClick(View v)
            {   

                        uname=username.getText().toString();
                        upass=password.getText().toString();
                        HttpClient client = new DefaultHttpClient();

                        tem="http://10.0.2.2:80/verify-login.php?username="+uname+"&password="+upass;
                        HttpGet request = new HttpGet(tem);
                        try
                        {
                            HttpResponse response=client.execute(request);
                            HttpEntity entity=response.getEntity();
                            InputStream is=entity.getContent();
                            InputStreamReader isr = new InputStreamReader(is);
                            BufferedReader reader = new BufferedReader(isr);
                            result=reader.readLine();   
                        } 

                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }

                        if(result.equals("0")==true)
                        {
                            Toast.makeText(getApplicationContext(), "Sorry try again", 1500).show();

                        }
                        else
                        {
                            Toast.makeText(getApplicationContext(), "Welcome Client", 1500).show();
                            myIntent=new Intent(login_page.this,Welcome_page.class);

                        }
                    }

        });

At the php script side. the code to fetch value from database and return to android is as below:

<?php

    mysql_connect("localhost","root","") or die(mysql_error());
    mysql_select_db("login") or die(mysql_error());

    $username=$_REQUEST['username'];
    $password=$_REQUEST['password'];
    $SelectQuery="select * from EmpLogin where C_Username='$username' and C_Password='$password'";
    $result=mysql_query($SelectQuery) or die(mysql_error());

    $count=mysql_num_rows($result);
    $row=mysql_fetch_array($result);
    if($count==0)
        echo "0";
    else
        echo $row['c_id'];
?>

This way you can fetch the value from DB and send back to android. hope this helps you. If you have any doubt then do ask me anytime.

这篇关于如何在Android中使用PHP脚本来获得MySQL数据库值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆