将Android连接到MySQL

时间:2015-01-21 11:34:20

标签: php android mysql

所以我对此非常陌生。我正在关注网络上的一个教程,该教程展示了如何连接这两个。但是我所做的一切都只是为了抓住一部分,它说“没有联系”#34;我错过了什么?我还连接到http服务器以使用PHP脚本从数据库中查询用户名和密码。

try
    {
        nameValuePairs = new ArrayList<NameValuePair>();

        nameValuePairs.add(new BasicNameValuePair("username", username));
        nameValuePairs.add(new BasicNameValuePair("password", password));

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        response = httpClient.execute(httpPost);

        if(response.getStatusLine().getStatusCode()==200)
        {
            entity = response.getEntity();

            if(entity != null)
            {
                InputStream instream = entity.getContent();

                JSONObject jsonResponse = new JSONObject(instream.toString());

                String retUser = jsonResponse.getString("upime");
                String retPass = jsonResponse.getString("geslo");

                if(username.equals(retUser) && password.equals(retPass))
                {
                    SharedPreferences sp = getSharedPreferences("logindetails", 0);

                    SharedPreferences.Editor spedit = sp.edit();

                    spedit.putString("upime", username);
                    spedit.putString("geslo", password);

                    spedit.commit();

                    Toast.makeText(getBaseContext(), "Login successful", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(getBaseContext(), "Failed to login", Toast.LENGTH_SHORT).show();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "No connection", Toast.LENGTH_LONG).show();
    }

3 个答案:

答案 0 :(得分:0)

您必须创建编写php代码的webservice。网络服务可以是肥皂和休息。你必须在http客户端对象中写下webservice的URL。

通过这样做,你可以连接android和mysql。

HttpPost postD=new HttpPost("url");

答案 1 :(得分:0)

您是否在Android清单中提供了Internet权限?

 <uses-permission android:name="android.permission.INTERNET" /> 

答案 2 :(得分:0)

 <?php 
 header('Content-Type: application/json'); 
 $dbhost ="localhost"; 
 $dbuser = "username"; 
 $dbpass = "password"; 
 $dbdb = "db"; 
 $connect = mysql_connect($db_host, $dbuser, $dbpass) or die("connection error"); 

 mysql_select_db($dbdb);
 $username =$_POST['username'];
 $password=$_POST['password'];
 $query = mysql_query("SELECT * FROM users WHERE user='$username' AND pass='$password'");

  $num = mysql_num_rows($query);
 if($num == 1) 
{ 
 while($list=mysql_fetch_assoc($query))
 { $output = $list; 
 }
  mysql_close(); 


 echo json_encode($output);


?>

将最终的&#34; echou&#34; 编辑为 echo 并添加

    header('Content-Type: application/json');