当前位置: 首页 > 知识库问答 >
问题:

无法使用php连接mysql数据库

毕黎昕
2023-03-14

我正在尝试连接我的android应用程序,该应用程序使用php将登录页面连接到数据库。它正在连接到数据库。但它并不是从表中检索所有列。相反,只获取两个冒号。下面是代码

    package com.example.hell;
    public class MainActivity extends Activity {
    Button btn;
    EditText ed;
     EditText ed1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final
    StrictMode.ThreadPolicy policy = new        StrictMode.ThreadPolicy.Builder().permitAll().build();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed=(EditText)findViewById(R.id.editText1);
        ed1= (EditText)findViewById(R.id.editText2);
        btn=(Button)findViewById(R.id.button1);

        btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
             String result = null;
             InputStream is = null;
             EditText editText = (EditText)findViewById(R.id.editText1);
             String v1 = editText.getText().toString();
             EditText editText1 = (EditText)findViewById(R.id.editText2);
             String v2 = editText1.getText().toString();

             ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

             nameValuePairs.add(new BasicNameValuePair("id",v1));
             nameValuePairs.add(new BasicNameValuePair("password",v2));
             StrictMode.setThreadPolicy(policy);
             try{
                 HttpClient httpclient=new DefaultHttpClient();
                 HttpPost httppost=new HttpPost("http://10.0.2.2/login.php");
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                 HttpResponse response = httpclient.execute(httppost); 
                 HttpEntity entity = response.getEntity();
                 is = entity.getContent();

                 Log.e("log_tag", "connection success ");
                 Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
             }
             catch(Exception e)
             {
                 Log.e("log_tag", "Error in http connection "+e.toString());
                  Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
             }
             try{
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                 StringBuilder sb = new StringBuilder();
                 String line = null;
                 while ((line = reader.readLine()) != null) 
                 {
                         sb.append(line + "\n");
                         Intent i = new Intent(getBaseContext(),Menu.class);
                         startActivity(i);
                 }

                 is.close();
                 result=sb.toString();
         }
         catch(Exception e)
         {
                Log.e("log_tag", "Error converting result "+e.toString());
            }

             try{


                JSONObject object = new JSONObject(result);
                 String ch=object.getString("re");
                 Toast.makeText(getApplicationContext(), ch, Toast.LENGTH_SHORT).show();

                 if(ch.equals("success"))
                 {

                   Intent i=new Intent("com.example.hell.MainActivity");
                   startActivity(i);
                 }


                 else
                 {

                     Toast.makeText(getApplicationContext(), "Record is not available.. Enter valid number", Toast.LENGTH_SHORT).show();

                 }


         }
         catch(JSONException e)
         {
                 Log.e("log_tag", "Error parsing data "+e.toString());
                 Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
         }  


        }
        });
      }

    @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;
    }

}

请帮我解决这个问题。

这里是登录表单的PHP代码

<?php
session_start();
$id=$_REQUEST["id"];
$password=$_REQUEST["password"];
if($id==NULL&& $password==NULL)
 {
    $r["re"]="Enter the Registered Id and password!!!";
                 print(json_encode($r));
                die('Could not connect: ' . mysql_error());
 }
 else
 {
  $connect=mysql_connect("localhost","root","") or die("couldn't connect");
  mysql_select_db("android") or die("couldn't find database");
  $query=mysql_query("SELECT * From profile WHERE username='$email'");
  $numrows=mysql_num_rows($query);
   while($rows=mysql_fetch_assoc($query))
    {
      $dbusername=$rows['id'];
      $dbpassword=$rows['password'];
    }
      if($id==$dbusername && $password==$dbpassword)
      {
   //  echo("you're in! <a href='member.php'>click</a>here to enter");
     //   $_SESSION ['email']=$dbusername;
     $r["re"]="success";
     print(json_encode($r));
      }
      else
      {
         $r["re"]="fail";
     print(json_encode($r));
      }
   }


?>

我的logcat显示以下错误。

03-23 05:50:37.970: E/AndroidRuntime(904): FATAL EXCEPTION: main
03-23 05:50:37.970: E/AndroidRuntime(904): Process: com.example.hell, PID: 904
03-23 05:50:37.970: E/AndroidRuntime(904): java.lang.NullPointerException
03-23 05:50:37.970: E/AndroidRuntime(904):  at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
03-23 05:50:37.970: E/AndroidRuntime(904):  at org.json.JSONTokener.nextValue(JSONTokener.java:94)
03-23 05:50:37.970: E/AndroidRuntime(904):  at org.json.JSONObject.<init>(JSONObject.java:155)
03-23 05:50:37.970: E/AndroidRuntime(904):  at org.json.JSONObject.<init>(JSONObject.java:172)
03-23 05:50:37.970: E/AndroidRuntime(904):  at com.example.hell.MainActivity$1.onClick(MainActivity.java:100)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.view.View.performClick(View.java:4424)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.view.View$PerformClick.run(View.java:18383)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.os.Handler.handleCallback(Handler.java:733)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.os.Handler.dispatchMessage(Handler.java:95)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.os.Looper.loop(Looper.java:137)
03-23 05:50:37.970: E/AndroidRuntime(904):  at android.app.ActivityThread.main(ActivityThread.java:4998)
03-23 05:50:37.970: E/AndroidRuntime(904):  at java.lang.reflect.Method.invokeNative(Native Method)
03-23 05:50:37.970: E/AndroidRuntime(904):  at java.lang.reflect.Method.invoke(Method.java:515)
03-23 05:50:37.970: E/AndroidRuntime(904):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-23 05:50:37.970: E/AndroidRuntime(904):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-23 05:50:37.970: E/AndroidRuntime(904):  at dalvik.system.NativeStart.main(Native Method)


thank u...but it shows stop working after click submit button

但它显示点击提交按钮后停止工作,我需要检索数据显示在Android模拟器上

包com。实例主要的导入java。木卫一。缓冲读取器;导入java。木卫一。输入流;导入java。木卫一。输入流阅读器;导入java。文本数字格式;导入java。util。ArrayList;

导入组织。阿帕奇。http。http实体;导入组织。阿帕奇。http。HttpResponse;导入组织。阿帕奇。http。名称值对;导入组织。阿帕奇。http。客户HttpClient;导入组织。阿帕奇。http。客户实体UrlEncodedFormEntity;导入组织。阿帕奇。http。客户方法。HttpPost;导入组织。阿帕奇。http。impl。客户默认HttpClient;导入组织。阿帕奇。http。消息基本名称对;导入组织。json。JSONException;导入组织。json。JSONObject;

导入android。注释。抑制皮棉;导入android。应用程序。活动导入android。操作系统。捆导入android。操作系统。严格模式;导入android。util。日志导入android。看法看法导入android。小装置。按钮导入android。小装置。编辑文本;导入android。小装置。干杯

@SuppressLint("NewApi")公共类选择扩展活动{@SuppressLint("NewApi")StrictMode。线程策略=新的StrictMode。线程策略。构建(). permitAll(). build();

 @SuppressLint("NewApi")    public void onCreate(Bundle savedInstanceState)
 {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select);

        Button button = (Button) findViewById(R.id.button1);
        StrictMode.setThreadPolicy(policy); 

        button.setOnClickListener(new View.OnClickListener()
        {
        public void onClick(View view)
          {
             String result = null;
            InputStream is = null;
            EditText editText = (EditText)findViewById(R.id.e1);
            String v1 = editText.getText().toString();
            EditText editText1 = (EditText)findViewById(R.id.e2);

            EditText editText2 = (EditText)findViewById(R.id.e3);

      ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            nameValuePairs.add(new BasicNameValuePair("f1",v1));
                try
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://10.0.2.2/select.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost); 
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();

                    Log.e("log_tag", "connection success ");


                }
            catch(Exception e)
                {
                    Log.e("log_tag", "Error in http connection "+e.toString());
                    Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();

                }
            //convert response to string
                try{
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) 
                    {
                            sb.append(line + "\n");

                    }
                    is.close();

                    result=sb.toString();
                }
                catch(Exception e)
                {
                   Log.e("log_tag", "Error converting result "+e.toString());

                Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();

                }

            //parse json data
            try{


                    JSONObject object = new JSONObject(result);
                    String ch=object.getString("re");
                    if(ch.equals("success"))
                    {

                       JSONObject no = object.getJSONObject("0");
                    String w= no.getString("f2");
                    long e=no.getLong("f3");

                    editText1.setText(w);
                   String myString = NumberFormat.getInstance().format(e);


                    editText2.setText(myString);

                      }


                    else
                    {

                        Toast.makeText(getApplicationContext(), "Record is not available.. Enter valid number", Toast.LENGTH_SHORT).show();

                    }


            }
            catch(JSONException e)
            {
                    Log.e("log_tag", "Error parsing data "+e.toString());
                    Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
            }


       }
       });



 }

}

共有1个答案

曹经业
2023-03-14

好啊我在php代码中看到,您只向客户机返回$r,因此它不包含任何有关概要文件的内容
所以您应该返回$row(编码为json

 类似资料:
  • 我无法使用客户机SquirrelSQL连接到MySQL。我以前曾设法连接到Oracle和Derby,但这次,我不知道我做错了什么。 我已经在我的Mac上安装了MySQL,以下步骤: > 要确保安装安全,请执行以下操作: 要创建新数据库: 要知道数据库存储在哪里: 创建一个表 在我遵循这些步骤之后: MySQL安装在/usr/local/ceral/MySQL/5.6.17下 在SQuirreL中,

  • 我在Spring是全新的,在Spring Hibernate无法连接到我的MySQL数据库。我得到 请求处理失败;嵌套异常为:org.springframework.transaction.CanNotCreateTransactionException: 无法打开事务的JPA EntityManager;嵌套异常为javax.persistence.persistenceException:or

  • 当我在Postman中点击url(http://localhost:8080/pjt/samples)以获取json数据时,它显示以下错误。 1)pom.xml 2)模型: .________/\/'___()____\\\\(()_'_''/'\\\\\\\/))()))'___.__,////===================================================

  • 我创建了一个简单的类来测试与我的localhost数据库的通信,这是我用Mysql Workbench创建的。Mysql服务器正在运行。JDBC驱动程序被添加到我的项目的类路径中。 当我运行程序时,我得到以下异常: 线程“main”com.mysql.cj.jdbc.Exceptions.CommunicationsException异常:通信链接失败 最后一个成功发送到服务器的数据包是在0毫秒前

  • 我正在尝试连接一个PHP脚本和一个数据库。但我总是犯同样的错误。 致命错误:未捕获错误:调用未定义的函数mysql_connect()在C:\xampp\htdocs\Datenbank\login.php:12堆栈跟踪:#0{main}抛出在第12行的C:\xampp\htdocs\Datenbank\login.php 这一错误发生在第12行。 但我做错了什么? 谢谢你的帮助。

  • 我最近做了一个项目,涉及使用java中的Swing在线连接到mysql数据库。然后我决定将项目转换为javaFX并尝试复制代码以连接到mysql数据库。 这是我的代码: 这是FXML文件的代码 然而,当我点击运行时,它就崩溃了,我得到错误“JavaSE二进制平台已经停止工作”。它在我以前使用摆动的应用程序中工作得很好。切换到javafx时,我所做的唯一改变是我使用了jdk 1.8而不是jdk 11