简体   繁体   English

使用php将mysql连接到Android应用时出错

[英]Error connecting mysql to Android app using php

I have a php script that connects android app with mysql DB but when I run it I have errors which I cannot not figure out. 我有一个将android应用程序与mysql DB连接的php脚本,但是当我运行它时,出现了我无法弄清的错误。

config.php config.php

<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'andro_test');?>

php script PHP脚本

<?php
//Start session
session_start();

//Include database connection details
require_once('config.php');

//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = false;

//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
    die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
    die("Unable to select database");
}

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return mysql_real_escape_string($str);
}

//Sanitize the POST values
$name = clean($_POST['name']);
$password = clean($_POST['password']);
$cpassword = clean($_POST['cpassword']);

//Input Validations
if($name == '') {
    $errmsg_arr[] = 'Login ID missing';
    $errflag = true;
}
if($password == '') {
    $errmsg_arr[] = 'Password missing';
    $errflag = true;
}
if($cpassword == '') {
    $errmsg_arr[] = 'Confirm password missing';
    $errflag = true;
}
if( strcmp($password, $cpassword) != 0 ) {
    $errmsg_arr[] = 'Passwords do not match';
    $errflag = true;
}

//Check for duplicate login ID
if($login != '') {
    $qry = "SELECT * FROM test WHERE name='$name'";
    $result = mysql_query($qry);
    if($result) {
        if(mysql_num_rows($result) > 0) {
                // here I want to show a msg that auto disappear...
            $errmsg_arr[] = 'username  already in use';    
            $_SESSION['errmsg'] = 'username  already in use';
            unset($_SESSION['errmsg']);

            $errflag = true;
        }
        @mysql_free_result($result);
    }
    else {
        die("Query failed");
    }
}

//If there are input validations, redirect back to the registration form
if($errflag) {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("location: D:\Third Year\FYP\dawah\arabteam\src\andro\website");// here I need my php to direct the user to my next android file ".java" under the app. file in my PC
    exit();
}

//Create INSERT query
$qry = "INSERT INTO test(name, password) VALUES('$name','".md5($_POST['password'])."')";
$result = @mysql_query($qry);

//Check whether the query was successful or not
if($result) {
                // here I want to show a msg that auto disappear...
    $errmsg_arr[] = 'succefull registeration';
                    $_SESSION['errmsg'] = 'succefull registeration';
                    unset($_SESSION['errmsg']);


            $errflag = true;
}else {
    echo("registeration failed");
}?>

my android app files 我的android应用文件

my main java file 我的主要Java文件

package andro.website;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ComminicateWithWebsiteActivity extends Activity 
{
TextView txtUserName;
TextView txtPassword;
TextView confpass;
Button btnReg;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    initComponents();
}
private void initComponents()
{
    txtUserName=(TextView)findViewById(R.id.txtUserName);
    txtPassword=(TextView)findViewById(R.id.txtPassword);
    confpass= (TextView)findViewById(R.id.confirmpassword);
    btnReg=(Button)findViewById(R.id.btnReg);
    btnReg.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            try
            {
                String usName=txtUserName.getText().toString();
                String pass=txtPassword.getText().toString();
                String url="http://10.0.2.2/register-exec.php?name="+usName+"&password="+pass;
                Server server=new Server(url, getApplicationContext());
                server.run();
            }
            catch(Exception c)
            {
                Log.e("Thread Exception", c.getMessage());
            }
        }
    });
}}

server file 服务器文件

package andro.website;

import java.io.BufferedReader;
import java.io.InputStreamReader;
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.util.Log;
import android.widget.Toast;

public class Server
{
String url;
Context context;

public Server(String url,Context context)
{
    this.url=url;
    this.context=context;
}

public void run()
{
        try
        {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url);
            Log.d("request", "done");
            HttpResponse response = client.execute(request);
            Log.d("respone", "done");
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            Log.d("Buffer", "readed");
            String line = "";
            while ((line = rd.readLine()) != null) 
            {
                Toast.makeText(context, line, Toast.LENGTH_LONG).show();
                Log.d("Toast", line);
            }
        }
        catch(Exception c)
        {
            Log.e("Exception",c.getMessage());
        }
}
}

my mainifest file 我的清单文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<EditText
    android:id="@+id/txtUserName"
    android:layout_width="160dp"
    android:layout_height="wrap_content"
    android:ems="10" >

    <requestFocus />
</EditText>


<EditText
    android:id="@+id/txtPassword"
    android:layout_width="178dp"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPassword" />

<Button
    android:id="@+id/btnReg"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="reg" />

<EditText
    android:id="@+id/confirmpassword"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPassword" />

the error I got deoesn't appear in my logcat rather it appears in the android VM screen 我得到的错误不会出现在我的logcat中,而是出现在android VM屏幕中

Although you did not mention what is the error exactly, but it is probably NetworkOnMainThreadException when you execute 尽管您没有确切提到错误是什么,但是执行时可能是NetworkOnMainThreadException

Server server=new Server(url, getApplicationContext());
server.run();

You should consider yousing AsynchTask ( see this example ) for your network operations 您应该考虑使用AsynchTask请参见本示例 )进行网络操作

A quick fix for your code is to let your Server class extends Thread and call server.start() instead of server.run() 您的代码的快速解决方案是让您的Server类扩展Thread并调用server.start()而不是server.run()

Edit: 编辑:

Also if there is not valid reason to use ApplicationContext , you should use your activity context, eg 另外,如果没有正当理由使用ApplicationContext ,则应使用活动上下文,例如

Server server=new Server(url, this);

if you want to use Toast from the server class, you have to run it in the UI thread by calling Activity.runOnUiThread 如果要从服务器类使用Toast ,则必须通过调用Activity.runOnUiThreadUI thread运行它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM