android如何用php页面代码连接到MySQL数据库?

时间:2016-01-09 10:40:11

标签: php android mysql eclipse

我想连接MySQL数据库但它没有用 我试过这段代码:

public void loginPost(View view){
  String username = usernameField.getText().toString();
  String password = passwordField.getText().toString();


  try{


  String link="http://mwssong.esy.es/android/Login.php";
  String data  = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
  data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

  URL url = new URL(link);
  URLConnection conn = url.openConnection(); 

  conn.setDoOutput(true); 
  OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 

  wr.write( data ); 
  wr.flush(); 

  BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

  StringBuilder sb = new StringBuilder();
  String line = null;

  // Read Server Response
  while((line = reader.readLine()) != null)
  {
     sb.append(line);
     break;
  } 

  if(sb.toString()=="admin")
      new AdminScreen();          
  else if(sb.toString()=="Customer")
  {

      Intent myIntent(view.getContext(),AdminScreen.class);
      startActivity(myIntent);
  }
  else
      status.setText(sb);
  }
  catch(Exception e){
      status.setText("Exception:   " + e.getMessage());
  }

}

但它总是在状态提示我的Exception null 并且Intent不起作用,Eclipse根本没有解决建议拒绝这个指令:

      Intent myIntent(view.getContext(),AdminScreen.class);
      startActivity(myIntent);

和php代码是:

<?php
$db = mysqli_connect('mysql.hostinger.ae','u641845309_ur','q1p0w2o9','u641845309_song');
// username and password sent from Form and protect MySQL injection for Security purpose
$username=mysqli_real_escape_string($db,$_POST['username']); 
$password=mysqli_real_escape_string($db,$_POST['password']); 

$sql="SELECT * FROM customer WHERE UName='$username' and Password='$password'";
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$result=mysqli_query($db,$sql);  

// If result matched $myusername and $mypassword, table row must be 1 row
if($result)
{ 
  while($row = mysqli_fetch_array($result)) {


// Redirecting To Other Page
if(strtolower($username)=='admin') 
echo  "Admin"; 
else 
echo  "Customer"; 
  }
}
else 
{
echo  "Your Login Name or Password is invalid"; 
}


?>

1 个答案:

答案 0 :(得分:0)

  

mysqli_query

     
    

失败时返回FALSE。成功的SELECT,SHOW,DESCRIBE或     EXPLAIN查询mysqli_query()将返回一个mysqli_result对象。对于     其他成功的查询mysqli_query()将返回TRUE。

  

所以在这种情况下(SELECT查询)你应该使用mysqli_num_rows来知道结果中的记录数,如果数字为零,则SELECT查询不返回任何记录,这意味着没有这样的用户名和密码
像这样:

if(mysqli_num_rows($result)>0){
  //code executed when username and password are found
} 
else {
  //code executed when no such username and password 
}