【问题标题】:Can't connect Android application to MySQL database using WAMP as local server无法使用 WAMP 作为本地服务器将 Android 应用程序连接到 MySQL 数据库
【发布时间】:2018-01-04 10:05:58
【问题描述】:

我正在尝试为我的 Android 应用程序创建一个简单的登录,该应用程序将用户的输入与数据库中的数据进行比较,遵循以下教程:

我使用 WAMP 作为本地服务器只是为了测试我是否可以建立连接。 我在以下目录中有两个名为 config.inc.phplogin.inc.php 的 PHP 文件:C:\wamp64\www\DUFT 他们看起来像这样:

config.inc.php

<?php $servername = "localhost:80"; 
  $username = "root";
  $password = "root";
  $dbname = "duft";

  try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
    die("OOPs something went wrong");
}

?>

login.inc.php

<?php

 include 'config.inc.php';

 // Check whether username or password is set from android  
 if(isset($_POST['username']) && isset($_POST['password']))
 {
      // Innitialize Variable
      $result='';
      $username = $_POST['username'];
      $password = $_POST['password'];

      // Query database for row exist or not
      $sql = 'SELECT * FROM tbl_login WHERE  email = :username AND adgangskode = :password';
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(':username', $username, PDO::PARAM_STR);
      $stmt->bindParam(':password', $password, PDO::PARAM_STR);
      $stmt->execute();
      if($stmt->rowCount())
      {
         $result="true";    
      }  
      elseif(!$stmt->rowCount())
      {
            $result="false";
      }

      // send result back to android
      echo $result;
}?>

然后我有我的 LoginActivity 类,我在其中使用 AsyncTask 在后台建立与数据库的连接。在 onPostExecute() 方法中,如果用户输入与数据库中的内容匹配,我将尝试启动一个新活动。但我不断从 PHP 文件中收到此错误:


( ! ) 警告: PDO::__construct(): MySQL 服务器在 C:\wamp64\www\DUFT\login.inc.php 行 10Call Stack#TimeMemoryFunctionLocation10.0042244400{main}( )...\login.inc.php:020.0043245592http://www.php.net/PDO.construct'target='_new'>__construct( )...\login.inc.php:10( ! ) 警告: PDO::__construct(): 读取问候包时出错。 PID=9636 在 C:\wamp64\www\DUFT\login.inc.php 行 10Call Stack#TimeMemoryFunctionLocation10.0042244400{main}( )...\login.inc.php:020.0043245592http://www.php.net/PDO.construct'target='_new'>__construct( )...\login.inc.php:10OOPs 出了点问题

这是我的 logcat 所说的:

我的 LoginActivity Java 类如下所示:

public class LoginActivity extends AppCompatActivity{

//NYT
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds

public static final int CONNECTION_TIMEOUT=2000000000;
public static final int READ_TIMEOUT=2000000000;
private EditText etEmail;
private EditText etPassword;
//NYT

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    //NYT
    // Get Reference to variables
    etEmail = (EditText) findViewById(R.id.eMail);
    etPassword = (EditText) findViewById(R.id.password);
    //NYT


    TextView klikHer = (TextView) findViewById(R.id.klikHer);
    klikHer.setPaintFlags(klikHer.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

    Button login = (Button) findViewById(R.id.signIn);
    login.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //Intent intent = new Intent(LoginActivity.this, MenuScreen.class);
            //startActivity(intent);

            //NYT
            // Get text from email and passord field
            final String email = etEmail.getText().toString();
            final String password = etPassword.getText().toString();

            // Initialize  AsyncLogin() class with email and password
            new AsyncLogin().execute(email, password);
            //NYT
        }
    });
}


private class AsyncLogin extends AsyncTask<String, String, String> {
    ProgressDialog pdLoading = new ProgressDialog(LoginActivity.this);
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL("http://192.168.87.100/DUFT/login.inc.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            //conn.setReadTimeout(READ_TIMEOUT);
            //conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // Append parameters to URL
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("username", params[0])
                    .appendQueryParameter("password", params[1]);
            String query = builder.build().getEncodedQuery();

            // Open connection for sending data
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "exception";
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "exception";
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread

        pdLoading.dismiss();

        if (result.equalsIgnoreCase("true")) {
            /* Here launching another activity when login successful. If you persist login state
            use sharedPreferences of Android. and logout button to clear sharedPreferences.
             */

            Intent intent = new Intent(LoginActivity.this, MenuScreen.class);
            startActivity(intent);
            LoginActivity.this.finish();

        } else if (result.equalsIgnoreCase("false")) {

            // If username and password does not match display a error message
            //Toast.makeText(LoginActivity.this, "Invalid email or password", Toast.LENGTH_LONG).Show();


        } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

            //Toast.makeText(LoginActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).Show();

        }
    }
}}

我已按照教程中的所有步骤进行操作,并且可以通过在移动浏览器中输入 IPv4 地址来使用手机访问本地服务器。这一定意味着我也可以访问这台本地服务器上的数据库,对吧?

【问题讨论】:

  • 在您的 httpd 配置文件中允许连接
  • 尝试删除 config.php 中的主机端口 :80 ..
  • @OussemaAroua 你能告诉我更具体的如何允许连接吗?
  • 使用 ** die("连接数据库失败:" . $ex->getMessage()); 更新 config.php 中的 catch 块**
  • @Omi 我更改了 catch 块,它现在给了我这个消息:无法连接到数据库:SQLSTATE[HY000] [2006] MySQL 服务器已消失

标签: php android wamp wampserver


【解决方案1】:

我找到了解决方案!问题出在这行代码

php $servername = "localhost:80"; 

这里我定义了 Apache 的端口,而不是 MySQL 的 3307。所以我只是把它改成了正确的端口,即 3307 :)

感谢您的帮助!

【讨论】:

  • 1) 关闭端口号:3307,它将采用 php.ini 中设置的默认值 2) MySQL 通常在端口 3306 上运行
  • 端口 3307 用于 MariaDB 的 WAMPServer 3.0.7 及更高版本
猜你喜欢
  • 2020-08-02
  • 2014-04-19
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2017-09-14
  • 2017-10-17
  • 2015-09-14
  • 1970-01-01
相关资源
最近更新 更多