Php 从android应用程序将数据插入MySQL

Php 从android应用程序将数据插入MySQL,php,android,mysql,json,jsonobject,Php,Android,Mysql,Json,Jsonobject,我打算为android开发一个web应用程序,但我第一次尝试这个实验,所以我无法完成我的任务,因为我是新手。它给了我一个类似字符串无法转换为JSONObject的错误。请帮帮我,我已经尽力了,但还没有找到任何解决办法。这是我的密码 public class signup extends Activity implements OnClickListener { Button signup,cancel; EditText e1,e2,e3,e4; String name; String ema

我打算为android开发一个web应用程序,但我第一次尝试这个实验,所以我无法完成我的任务,因为我是新手。它给了我一个类似字符串无法转换为JSONObject的错误。请帮帮我,我已经尽力了,但还没有找到任何解决办法。这是我的密码

public class signup extends Activity implements OnClickListener {
Button signup,cancel;
EditText e1,e2,e3,e4;

String name;
String email;
String  mobile;
String passwd;
InputStream is=null;
String result=null;
String line=null;
int code;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.signupfrag);

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    signup=(Button)findViewById(R.id.reg);
    cancel=(Button)findViewById(R.id.regcancel);

    e1=(EditText)findViewById(R.id.name);
    e2=(EditText)findViewById(R.id.uid);
    e3=(EditText)findViewById(R.id.contact);
    e4=(EditText)findViewById(R.id.passwd); 

    signup.setOnClickListener(this);
    cancel.setOnClickListener(this);
}
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId()==R.id.reg)
    {
        name = e1.getText().toString();
        email = e2.getText().toString();
        mobile = e3.getText().toString();
        passwd = e4.getText().toString();

        insert();
      Intent i=new Intent(signup.this,MainActivity.class);
      startActivity(i);
    }

    if(v.getId()==R.id.regcancel)
    {
      e1.setText(null);
      e2.setText(null);
      e3.setText(null);
      e4.setText(null);
    }
}
private void insert() {
    // TODO Auto-generated method stub
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();


    nameValuePairs.add(new BasicNameValuePair("fname",name));
    nameValuePairs.add(new BasicNameValuePair("email",email));
    nameValuePairs.add(new BasicNameValuePair("mobile",mobile));
    nameValuePairs.add(new BasicNameValuePair("passwd",passwd));

        try
        {
        HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.43.73/htdocs/insert1.php");//10.0.2.2
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("pass 1", "connection success ");
    }
        catch(Exception e)
    {
            Log.e("Fail 1", e.toString());
            Toast.makeText(getApplicationContext(), "Invalid IP Address",
            Toast.LENGTH_LONG).show();
    }     

        try
        {
            BufferedReader reader = new BufferedReader
            (new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null)
        {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        Log.e("pass 2", "connection success ");
    }
        catch(Exception e)
    {
            Log.e("Fail 2", e.toString());
    }     

    try
    {
            JSONObject json_data = new JSONObject(result);
            code=(json_data.getInt("code"));

            if(code==1)
            {
        Toast.makeText(getBaseContext(), "Inserted Successfully",
            Toast.LENGTH_SHORT).show();
            }
            else
            {
         Toast.makeText(getBaseContext(), "Sorry, Try Again",
            Toast.LENGTH_LONG).show();
            }
    }
    catch(Exception e)
    {
        Log.e("log_tag", "Error parsing data "+e.toString());
        Log.e("log_tag", "Failed data was:\n" + result);
            Log.e("Fail 3", e.toString());
    }       
  }
}
公共类注册扩展活动实现OnClickListener{
按钮注册,取消;
编辑文本e1、e2、e3、e4;
字符串名;
字符串电子邮件;
字符串移动;
字符串密码;
InputStream=null;
字符串结果=null;
字符串行=null;
int代码;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.signupfrag);
如果(android.os.Build.VERSION.SDK_INT>9){
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(策略);
}
注册=(按钮)findViewById(R.id.reg);
cancel=(按钮)findviewbyd(R.id.regcancel);
e1=(EditText)findViewById(R.id.name);
e2=(EditText)findViewById(R.id.uid);
e3=(EditText)findViewById(R.id.contact);
e4=(EditText)findViewById(R.id.passwd);
signup.setOnClickListener(this);
cancel.setOnClickListener(此);
}
公共void onClick(视图v){
//TODO自动生成的方法存根
如果(v.getId()==R.id.reg)
{
name=e1.getText().toString();
email=e2.getText().toString();
mobile=e3.getText().toString();
passwd=e4.getText().toString();
插入();
意向i=新意向(signup.this,MainActivity.class);
星触觉(i);
}
if(v.getId()==R.id.regcancel)
{
e1.setText(空);
e2.setText(空);
e3.setText(空);
e4.setText(空);
}
}
专用空白插入(){
//TODO自动生成的方法存根
ArrayList nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“fname”,name));
添加(新的BasicNameValuePair(“email”,email));
添加(新的BasicNameValuePair(“mobile”,mobile));
添加(新的BasicNameValuePair(“passwd”,passwd));
尝试
{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://192.168.43.73/htdocs/insert1.php");//10.0.2.2
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
is=entity.getContent();
Log.e(“通过1”,“连接成功”);
}
捕获(例外e)
{
Log.e(“Fail 1”,e.toString());
Toast.makeText(getApplicationContext(),“无效IP地址”,
Toast.LENGTH_LONG).show();
}     
尝试
{
BufferedReader reader=新的BufferedReader
(新的InputStreamReader(is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
而((line=reader.readLine())!=null)
{
sb.追加(第+行“\n”);
}
is.close();
结果=sb.toString();
Log.e(“通过2”,“连接成功”);
}
捕获(例外e)
{
Log.e(“Fail 2”,e.toString());
}     
尝试
{
JSONObject json_data=新的JSONObject(结果);
code=(json_data.getInt(“code”);
如果(代码==1)
{
Toast.makeText(getBaseContext(),“已成功插入”,
吐司。长度(短)。show();
}
其他的
{
Toast.makeText(getBaseContext(),“抱歉,再试一次”,
Toast.LENGTH_LONG).show();
}
}
捕获(例外e)
{
Log.e(“Log_标记”,“错误解析数据”+e.toString());
Log.e(“日志标签”,“失败数据为:\n”+结果);
Log.e(“Fail 3”,e.toString());
}       
}
}
这是我的php代码

<?php
$host='127.0.0.1';
$uname='root';
$pwd='password';
$db="resumemaker";


$con = mysql_connect("localhost", "root");
mysql_select_db($db,$con) or die("db selection failed");

$fname=$_REQUEST['fname'];
$email=$_REQUEST['email'];
$mobile=$_REQUEST['mobile'];
$passwd=$_REQUEST['passwd'];



$flag['code']=0;

if($r=mysql_query("insert into sample values('$fname','$email','$mobile','$passwd') ",$con))
{
    $flag['code']=1;
    //echo"hi";
}

print(json_encode($flag));
mysql_close($con);
?>

您没有将其编码为json。此示例将帮助您实现其100%的工作代码

Index.php

<?php

   header("Content-Type:application/json");

   include("function.php");

$fname=$_REQUEST['fname'];
$email=$_REQUEST['email'];
$mobile=$_REQUEST['mobile'];
$passwd=$_REQUEST['passwd'];

 $record = fetchrecord($fname,$email,$mobile,$passwd);


         if(empty($record))
         {
           deliverresponse(200,"Record not found",NULL,0);  
         }
         else
         {
           deliverresponse(200,"Record Displayed",$record,1);   
         }


   function deliverresponse($status,$status_message,$data,$success)
   {
         header("HTTP/1.1 $status $status_message");
         $response['status'] = $status;
         $response['status_message'] = $status_message;
          $response['code'] = $code;
          $response['data'] = $data;
          $jsonresponse = json_encode($response);
          echo $jsonresponse;

   }
?>

是什么导致了PHP或…(c#?)的错误?您的PHP当前对SQL注入开放。它在logcat日志07-06 00:29:46.022:E/Fail 3(686):org.json.JSONException:值中显示错误,该值看起来不像PHP错误。这是java的第一段代码吗?可能要将该标记添加到此问题。此外,您还应该解决PHP代码中的SQL注入问题,并切换到
mysqli
pdo
驱动程序。我认为这是一个错误,请尝试{JSONObject json_data=new JSONObject(result);code=(json_data.getInt(“code”);if(code==1){Toast.makeText(getBaseContext(),“Inserted Successfully”,Toast.LENGTH_SHORT.show();}else{Toast.makeText(getBaseContext(),“对不起,再试一次”,Toast.LENGTH_LONG.show();}}catch(异常e){Log.e(“Fail 3”,e.toString());}
<?php
        $conn = mysql_connect("localhost", "root", "");

        mysql_select_db('your db name', $conn);

  function fetchrecord($fname,$email,$mobile,$passwd)
  {


     $qur = mysql_query("INSERT INTO `sample` (fname,email,mobile,passwd) VALUES (NULL, '$fname','$email','$mobile','$passwd')") or die ("Query Failed");

     if($qur)
     {
        $msg = "Record Inserted";   

        $user[] = array($msg); 

     }
     else
     {
       $msg = "Record not Inserted";   

        $user[] = array($msg);   
     }
        return $user;

  }
 public class SignupProcess extends  AsyncTask<String, String, String>

    {
        JSONObject json = new JSONObject();
   private static final String TAG_SUCCESS = "code";
        @Override
        protected void onPreExecute() {

            pDialog = new ProgressDialog(signup.this);
            pDialog.setMessage("Login..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {




            List<NameValuePair> pair = new ArrayList<>();
            pair.add(new BasicNameValuePair("name", name));
            pair.add(new BasicNameValuePair("email", email));
            pair.add(new BasicNameValuePair("password", mobile));
            pair.add(new BasicNameValuePair("status",String,psswd);


            json = JSONParser.makeHttpRequest("http://xxxxxxx","GET", pair);

            Log.d("Create Response", json.toString());

            try {

                int success = json.getInt(TAG_SUCCESS);
                getstatus = success;
                if (success == 1) {

                    Log.d("success!", json.toString());

                }

                else if (success==0){


                    return json.getString(TAG_SUCCESS);

                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    public static String Result=null;

    public JSONParser()
    {

    }

    public static JSONObject makeHttpRequest(String url,String method, List<NameValuePair>  pair) {

        try {

            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(pair));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method.equals("GET")){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(pair, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, HTTP.UTF_8), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Result = json;
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return jObj;
    }


}
new SignupProcess().execute();