Android WAMP连接:屏幕上出现意外输出

时间:2014-08-05 14:09:56

标签: php android mysql wamp

我使用WAMP服务器从我的Android应用程序连接到MYSQL数据库。

在textview中我应该从数据库中的列中获取信息,我得到以下信息:

<!DOCTYPE html PUBLIC//WC3//DTD XHTML 1.0 strict/EN "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>

这是否意味着存在连接问题?

为什么会显示?

如果需要,我可以发布与PHP脚本和Activity相关的代码。

编辑:

Php脚本:

<?php

//load and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {
    //gets user's info based off of a username.
    $query = " 
            SELECT 
                id, 
                username, 
                password
            FROM users 
            WHERE 
                username = :username 
        ";

    $query_params = array(
        ':username' => $_POST['username']
    );

    try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {
        // For testing, you could use a die and message. 
        //die("Failed to run query: " . $ex->getMessage());

        //or just use this use this one to product JSON data:
        $response["success"] = 0;
        $response["message"] = "Database Error1. Please Try Again!";
        die(json_encode($response));

    }

    //This will be the variable to determine whether or not the user's information is correct.
    //we initialize it as false.
    $validated_info = false;

    //fetching all the rows from the query
    $row = $stmt->fetch();
    if ($row) {
        //if we encrypted the password, we would unencrypt it here, but in our case we just
        //compare the two passwords
        if ($_POST['password'] === $row['password']) {
            $login_ok = true;
        }
    }

    // If the user logged in successfully, then we send them to the private members-only page 
    // Otherwise, we display a login failed message and show the login form again 
    if ($login_ok) {
        $response["success"] = 1;
        $response["message"] = "Login successful!";
        die(json_encode($response));
    } else {
        $response["success"] = 0;
        $response["message"] = "Invalid Credentials!";
        die(json_encode($response));
    }
} else {
?>
        <h1>Login</h1> 
        <form action="login.php" method="post"> 
            Username:<br /> 
            <input type="text" name="username" placeholder="username" /> 
            <br /><br /> 
            Password:<br /> 
            <input type="password" name="password" placeholder="password" value="" /> 
            <br /><br /> 
            <input type="submit" value="Login" /> 
        </form> 
        <a href="register.php">Register</a>
    <?php
}

?> 

相关的Android活动:

登录活动:

package com.example.phpmysql;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;

public class SigninActivity  extends AsyncTask<String,Void,String>{

   private TextView statusField,roleField;
   private Context context;
   private int byGetOrPost = 0; 

   //flag 0 means get and 1 means post.(By default it is get.)
   public SigninActivity(Context context,TextView statusField,
   TextView roleField,int flag) {
      this.context = context;
      this.statusField = statusField;
      this.roleField = roleField;
      byGetOrPost = flag;
   }

   protected void onPreExecute(){

   }
   @Override
   protected String doInBackground(String... arg0) {
      if(byGetOrPost == 0){ //means by Get Method
         try{
            String username = (String)arg0[0];
            String password = (String)arg0[1];
//            String link = "http://myphpmysqlweb.hostei.com/login.php?username=" NOTE: APP WORKS WHEN USING THIS LINK
//            +username+"&password="+password;
            //note: this was changed from "http://localhost/login.php?username=" ATTEMPTING TO USE ON LOCALHOST NOT WORKING
//            String link = "http://192.168.56.1/login.php?username=" 
//                    +username+"&password="+password;

            //attmepting to run app using the php script hosting on the queens network
            String link = "http://web2.eeecs.qub.ac.uk/40006697/login.php?username=" 
                 +username+"&password="+password;
            URL url = new URL(link);
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(link));
            HttpResponse response = client.execute(request);
            BufferedReader in = new BufferedReader
           (new InputStreamReader(response.getEntity().getContent()));

           StringBuffer sb = new StringBuffer("");
           String line="";
           while ((line = in.readLine()) != null) {
              sb.append(line);
              break;
            }
            in.close();
            return sb.toString();
      }catch(Exception e){
         return new String("Exception: " + e.getMessage());
      }
      }
      else{
         try{
            String username = (String)arg0[0];
            String password = (String)arg0[1];     
            String link="http://web2.eeecs.qub.ac.uk/40006697/loginpost.php"; //attmepting to connect on network
            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;
            }
            return sb.toString();
         }catch(Exception e){
            return new String("Exception: " + e.getMessage());
         }
      }
   }
   @Override
   protected void onPostExecute(String result){
      this.statusField.setText("Login Successful");
      this.roleField.setText(result);
   }
}

MainActivity:

 package com.example.phpmysql;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;

    public class MainActivity extends Activity {

       private EditText usernameField,passwordField;
       private TextView status,role,method;

       @Override 
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          usernameField = (EditText)findViewById(R.id.editText1);
          passwordField = (EditText)findViewById(R.id.editText2);
          status = (TextView)findViewById(R.id.textView6);
          role = (TextView)findViewById(R.id.textView7);
          method = (TextView)findViewById(R.id.textView9);
       }
       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.main, menu);
          return true;
       }
       public void login(View view){
          String username = usernameField.getText().toString();
          String password = passwordField.getText().toString();
          method.setText("Get Method");
          new SigninActivity(this,status,role,0).execute(username,password);

       }
       public void loginPost(View view){
          String username = usernameField.getText().toString();
          String password = passwordField.getText().toString();
          method.setText("Post Method");
          new SigninActivity(this,status,role,1).execute(username,password);

       }

    }

1 个答案:

答案 0 :(得分:0)

尝试更改此代码以不使用die()它不是很好地终止脚本的好方法,并且可能生成一些html来包装错误消息。

// If the user logged in successfully, then we send them to the private members-only page 
// Otherwise, we display a login failed message and show the login form again 
if ($login_ok) {
    $response["success"] = 1;
    $response["message"] = "Login successful!";
    echo json_encode($response);
    exit;
} else {
    $response["success"] = 0;
    $response["message"] = "Invalid Credentials!";
    echo json_encode($response);
    exit;
}