2016-01-09 57 views
0

我想连接MySQL数据库和它没有工作 我试过这段代码:如何使用php页面代码连接到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()); 
    } 

}

但它总是给我的状态提起异常空 和意图不工作, 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"; 
} 


?> 
+0

这段代码没有连接到mysql数据库,它连接到一个php页面。 – Shadow

+0

对不起,我忘了php代码: 这是我的: –

+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 
} 
+0

我刚刚试过了.. –

+0

结果相同.. –

+0

“Exception null” –