简体   繁体   English

上传一个变量到sql查询

[英]Upload a variable to sql query

In my app I want to fetch JSON data from a server.在我的应用程序中,我想从服务器获取 JSON 数据。 For that I want the user to enter a variable that goes into the fetching query, but the way I tried it my app doesn't get any response from the server:为此,我希望用户输入一个进入获取查询的变量,但我尝试的方式我的应用程序没有从服务器得到任何响应:

<?php

$conn = new mysqli($servername, $username, $password, $dbname);

if(isset($_POST['name'])){
 $query = "INSERT INTO TestTable (name) VALUES ('$_POST[name]')";

 if(mysqli_query($conn,$query)){ 
     echo 'Data Submit Successfully';
 }else{
     echo 'Try Again';
 }    
}


$var = $_POST['name'];

 $query = "SELECT * FROM TestTable WHERE id = '$var'";

    $result = mysqli_query($conn, $query);

    while($row = mysqli_fetch_assoc($result)) {
        $array[] = $row;
    }


    header('Content-Type:Application/json');
    echo json_encode($array);
    mysqli_close($conn);

?>

The uploaded variable is posted into the table as it should do.上传的变量按它应该做的那样发布到表中。 And If I set $var to a fixed value I do get a correct response.如果我将$var设置$var固定值,我会得到正确的响应。 But what do I have to change so that my posted Variable gets into the selecting query?但是我必须改变什么才能让我发布的变量进入选择查询?

Edit: here is the code of my uploading the variable and fetching the result - the GetData() and the InsertData() methods are used to upload and the other two to fetch:编辑:这是我上传变量并获取结果的代码 - GetData()InsertData()方法用于上传,另外两个方法用于获取:

 public class MainActivity extends AppCompatActivity {

    List<GetDataAdapter> GetDataAdapter1;
    RecyclerView recyclerView;
    RecyclerView.LayoutManager recyclerViewlayoutManager;
    RecyclerView.Adapter recyclerViewadapter;
    ProgressBar progressBar;

    String ServerURL = "https://x.com/test.php";
    EditText name;
    Button button;
    String TempName;
    String JSON_ID = "id";
    String JSON_NAME = "name";

    JsonArrayRequest jsonArrayRequest;
    com.android.volley.RequestQueue requestQueue;

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

        GetDataAdapter1 = new ArrayList<>();
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
        progressBar = (ProgressBar) findViewById(R.id.progressBar1);
        button = (Button) findViewById(R.id.button);
        recyclerView.setHasFixedSize(true);
        recyclerViewlayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(recyclerViewlayoutManager);
        name = (EditText) findViewById(R.id.editText);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                GetData();
                InsertData(TempName);
                JSON_DATA_WEB_CALL();
            }
        });
    }

    public void GetData() {
        TempName = name.getText().toString();
    }

    public void InsertData(final String a) {

        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {

                String NameHolder = a;

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

                nameValuePairs.add(new BasicNameValuePair("name", NameHolder));

                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(ServerURL);
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();


                    String responseStr = EntityUtils.toString(resEntity).trim();
                    Log.v("TAG 2", "Response: " +  responseStr);



                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                }
                return "Data Inserted Successfully";
            }

            @Override
            protected void onPostExecute(String result) {

                super.onPostExecute(result);

                Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();

            }
        }

        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

        sendPostReqAsyncTask.execute(a);
    }

    public void JSON_DATA_WEB_CALL() {

        jsonArrayRequest = new JsonArrayRequest(ServerURL,

                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        progressBar.setVisibility(View.GONE);
                        JSON_PARSE_DATA_AFTER_WEBCALL(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(jsonArrayRequest);

    }

    public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {

        for (int i = 0; i < array.length(); i++) {

            GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
            JSONObject json = null;
            try {
                json = array.getJSONObject(i);
                GetDataAdapter2.setId(json.getInt(JSON_ID));
                GetDataAdapter2.setName(json.getString(JSON_NAME));

            } catch (JSONException e) {

                e.printStackTrace();
            }
            GetDataAdapter1.add(GetDataAdapter2);
        }

        recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
        recyclerView.setAdapter(recyclerViewadapter);
    }
}

I suggest defining your post variable我建议定义你的帖子变量

$postVar = $_POST['variable'];

Then you should probably sanitise it before putting it in your SQL string.那么您应该在将其放入 SQL 字符串之前对其进行消毒。

I would prefer to use Prepared Statements.我更喜欢使用准备好的语句。 You should read about them herehttps://www.w3schools.com/php/php_mysql_prepared_statements.asp and use them instead as it fits your case exactly您应该在此处阅读有关它们的信息https://www.w3schools.com/php/php_mysql_prepared_statements.asp并改用它们,因为它完全适合您的情况

Edit: How did you determine that your SELECT query didn't execute?编辑:你是如何确定你的 SELECT 查询没有执行的?

Edit 2: So I tested out modified version of your code:编辑 2:所以我测试了你的代码的修改版本:

if(isset($_GET['name'])){
   $query = "INSERT INTO TestTable (name) VALUES ('$_GET[name]')";
   echo $query;
   echo "</br></br>";
}

$var = "$_GET[name]";
echo $var;
echo "</br></br>";

$query = "SELECT * FROM TestTable WHERE name = '$var'";
echo $query;

The output that this produced by going to fileName.php?name=getVariableCorrectlyPopulated is:通过转到fileName.php?name=getVariableCorrectlyPopulated产生的输出是:

INSERT INTO TestTable (name) VALUES ('getVariableCorrectlyPopulated')

getVariableCorrectlyPopulated

SELECT * FROM TestTable WHERE name = 'getVariableCorrectlyPopulated'

As you can see that is with GET instead of POST but data is going in correctly, I suggest you do the same or similar when you first make your scripts.You can use XAMPP (for example) for Apache distribution and run your scripts locally.如您所见,使用 GET 而不是 POST 但数据正确输入,我建议您在第一次制作脚本时执行相同或类似的操作。您可以使用 XAMPP(例如)进行 Apache 分发并在本地运行您的脚本。

Edit 3+4:编辑 3+4:

Tested and is working:已测试并正在工作:

<?php
if(isset($_POST['name'])){
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";
    $conn = new mysqli($servername, $username, $password, $dbname);

    $array=array();
    $postVar =  $_POST['name'];
    //DONT FORGET TO SANITIZE

    $query1 = "INSERT INTO TestTable (name) VALUES ('$postVar')";
    if(mysqli_query($conn,$query1, false)){
//        echo 'Data Submit Successfully';
    }else{
        echo 'Try Again';
    }

    $query2 = "SELECT * FROM TestTable WHERE name = '$postVar'";
    $result = mysqli_query($conn, $query2);
    while($row = mysqli_fetch_assoc($result)) {
        $array[] = $row['name'];
    }

    echo json_encode($array);
}
?>

Please keep in mind there are way better ways to do this... See Prepared Statements above请记住,有更好的方法可以做到这一点......请参阅上面的准备好的声明

Edit 5: You should change your code to what I gave you in Edit 3+4 (and sanitise the post data as well) and edit your android code so that you handle the response from doInBackground method https://developer.android.com/reference/android/os/AsyncTask .编辑 5:您应该将代码更改为我在编辑 3+4 中给您的代码(并清理发布数据)并编辑您的 android 代码,以便您处理来自doInBackground方法的响应https://developer.android.com /reference/android/os/AsyncTask

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

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