php - 使用 json 中的子句从数据库读取数据

标签 php android mysql json database

我编写了一个程序,想要从数据库读取一些数据,它显示我在数据库中创建的周六表中存在的所有数据,但我想使用子句来显示一些数据。实际上,在这个程序中,我想仅显示每个登录者的数据,并且他的名字位于我称之为 whoo 的字符串中(查看 android 代码); 如何将其更改为仅读取与登录者相关的数据。 在我的表中有一行我称之为 user_name ,在 android 代码中我有一个名为 whoo 的字符串,我想用这个子句显示数据: WHERE 用户名 = '$用户名' 请帮我... 我用 PHP 和 json 编写这个程序 这是我的代码:

php:

<?php


$con = mysql_connect("...","...","....");

mysql_select_db("...",$con);

$response=array();
$result=mysql_query("select * from saturday");

if(mysql_num_rows($result)>0){

$response["saturday"]=array();

while($row=mysql_fetch_array($result)){
    $temp=array();
    $temp["username"]=$row["user_name"];
    $temp["userside"]=$row["user_sideup"];
    $temp["userchair"]=$row["user_chair"];
    $temp["userjump"]=$row["user_jump"];
    $temp["userstep"]=$row["user_step"];
    $temp["usercalf"]=$row["user_calf"];



    array_push($response["saturday"],$temp);


}

$response["t"]=1;
echo json_encode($response);



}else{

$response["t"]=0;
$response["message"]="not fonud";
echo json_encode($response);

}


?>

这是我的安卓:

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class ResultPage extends ListActivity {

private ProgressDialog pd;
JSONParser jparser = new JSONParser();
ArrayList<HashMap<String, String>> P;



JSONArray s = null;
private static String url = "http://akosamanus.xzn.ir/getsaturday.php";

TextView who,which;


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



    who = (TextView)findViewById(R.id.who);
    which = (TextView)findViewById(R.id.which);


    Bundle extras = getIntent().getExtras();
    String whoo = extras.getString("uname");
    String whiche = extras.getString("uday");

    who.setText(whoo);
    which.setText(whiche);

    P = new ArrayList<HashMap<String, String>>();
    new result().execute();
}





@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    String zname = ((TextView) v.findViewById(R.id.tvsetname)).getText().toString();
    String zside = ((TextView) v.findViewById(R.id.tvsetside)).getText().toString();
    String zstep = ((TextView) v.findViewById(R.id.tvsetstep)).getText().toString();
    String zcalf = ((TextView) v.findViewById(R.id.tvsetcalf)).getText().toString();
    String zjump = ((TextView) v.findViewById(R.id.tvsetjump)).getText().toString();
    String zchair = ((TextView) v.findViewById(R.id.tvsetchair)).getText().toString();
    Intent intent = new Intent(ResultPage.this,CResultPage.class);

    intent.putExtra("zside",zside);
    intent.putExtra("zstep",zstep);
    intent.putExtra("zcalf",zcalf);
    intent.putExtra("zjump",zjump);
    intent.putExtra("zchair",zchair);
    startActivityForResult(intent,1);


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode==1){
        if(data.hasExtra("Result")){

        }
    }
}


class result extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(ResultPage.this);
        pd.setMessage("loading...");
        pd.show();
    }


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



        // ContentValues params = new ContentValues();
        List<NameValuePair> params = new ArrayList<NameValuePair>(); // Building Parameters

        // getting JSON string from URL
        JSONObject json = jparser.makeHttpRequest(url, "GET", params);


        try {
            int t = json.getInt("t");

            if (t==1){
                s=json.getJSONArray("saturday");
                for (int i=0;i<s.length();i++){
                    JSONObject c=s.getJSONObject(i);
                    String username=c.getString("username");
                    String userside=c.getString("userside");
                    String userchair=c.getString("userchair");
                    String userjump=c.getString("userjump");
                    String userstep=c.getString("userstep");
                    String usercalf=c.getString("usercalf");
                    String today=which.getText().toString();


                    HashMap<String,String> map=new HashMap<String,String>();
                    map.put("username",username);
                    map.put("userside",userside);
                    map.put("userchair",userchair);
                    map.put("userjump",userjump);
                    map.put("userstep",userstep);
                    map.put("usercalf", usercalf);
                    map.put("Saturday", today);


                    P.add(map);



                }


            }else {
                Toast.makeText(ResultPage.this, "ooooooooooops", Toast.LENGTH_SHORT).show();
            }


        } catch (JSONException e) {
            e.printStackTrace();

        }


        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        pd.dismiss();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ListAdapter adapter=new SimpleAdapter(ResultPage.this,P,R.layout.item_list2,
                        new  String[]{"username","userside","userchair","userjump","userstep","usercalf","Saturday"},
                        new  int[]{R.id.tvsetname,R.id.tvsetside,R.id.tvsetchair,R.id.tvsetjump,R.id.tvsetstep
                                ,R.id.tvsetcalf,R.id.tvsetday});

                setListAdapter(adapter);




            }
        });

    }

}

}

<小时/>
08-14 13:14:11.433    4305-4305/com.example.eagle.start1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.eagle.start1, PID: 4305
android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
        at java.net.InetAddress.getAllByName(InetAddress.java:215)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:142)
        at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
        at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
        at com.example.eagle.start1.JSONParser.makeHttpRequest(JSONParser.java:118)
        at com.example.eagle.start1.ResultPage$result$1.run(ResultPage.java:135)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

最佳答案

为了从数据库获取特定值,我们必须使用 GET 或 POST 方法 所以在这里我修改了您的 PHP 代码(使用 GET 方法)。

<?php
    $con = mysql_connect("...","...","....");

    mysql_select_db("...",$con);

    if (isset($_GET["username"])) {
        $username = $_GET['username'];

    $response=array();
    $result=mysql_query("select * from saturday where user_name= $username");

    if(mysql_num_rows($result)>0){

    $response["saturday"]=array();

    while($row=mysql_fetch_array($result)){
        $temp=array();
        $temp["username"]=$row["user_name"];
        $temp["userside"]=$row["user_sideup"];
        $temp["userchair"]=$row["user_chair"];
        $temp["userjump"]=$row["user_jump"];
        $temp["userstep"]=$row["user_step"];
        $temp["usercalf"]=$row["user_calf"];



        array_push($response["saturday"],$temp);


    }

    $response["t"]=1;
    echo json_encode($response);



    }else{

    $response["t"]=0;
    $response["message"]="not fonud";
    echo json_encode($response);

    }

    }
    ?>

在 Android 端,您必须在 NameValuePair 中传递 user_name,如下所示

 List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username",who.getText()));
        final JSONObject json = jParser.makeHttpRequest(url, "GET", params);

如果您有任何疑问,请观看this或在下面评论:) 快乐编码!

关于php - 使用 json 中的子句从数据库读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38931983/

相关文章:

php - php 中出现 MySQL 错误,但 phpmyadmin 中没有错误

javascript - 如何在 $.ajax 中沿着 FormData 传递附加参数

android - 一个Java问题,但是一个Android问题,这里是为什么:

mysql - 计算出现次数

mysql - 应用错误 1677 : Column 59 of table `sales_orders` cannot be converted from type `datetime` to type `varchar(10)`

javascript - 循环数组以修改值(JavaScript 到 PHP 并返回到 JavaScript)

android - sdk platform-tools (23.1) 太旧,无法检查使用 API 24 编译的 API;请更新

android - gridview底部的ProgressBar

php - 如何在where条件下传递数组?拉维尔 5.3

php - 指向友好 URL 的 HTML 表单