When inserting data from Android to MySQL, why is all the data inserted with the number "1"?
When I insert it directly from the console, it inserts normally. What’s the problem?
This is my PHP code:
<?php
$con = mysqli_connect("localhost", "root", "", "lice");
mysqli_query($con, 'SET NAMES utf8');
$name = isset($_POST["name"]);
$statement = mysqli_prepare($con, "INSERT INTO USER(NAME) VALUES (?)");
mysqli_stmt_bind_param($statement, "s", $name);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
This is part of Activity code:
public void onClick(DialogInterface dialog, int whichButton) {
name = uname.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if(success){
Toast.makeText(getApplicationContext(), name + "success", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
};
UserRequest userRequest = new UserRequest(name, responseListener);
RequestQueue queue = Volley.newRequestQueue( UserActivity.this );
queue.add(userRequest);
}
});
This is Request code:
public class UserRequest extends StringRequest {
final static private String URL = "my url";
private Map<String, String> parameters;
public UserRequest(String name, Response.Listener<String> listener) {
super(Method.POST, URL, listener, null);
parameters = new HashMap<>();
parameters.put("name", name);
}
@Override
public Map<String, String> getParams() {
return parameters;
}
}
2
Answers
isset()
returns a boolean , true or false, which can equate to 1 or ”so
will set
$name
to 1 or ”Instead try
which checks that the value is set and if so moves it to the
$name
var otherwise it set it to''
Which probably means you should do a bit more checking before using it in a query like
This is the value you’re inserting:
Per the documentation,
isset
returns abool
. So you’re not inserting a "name", you’re inserting "whether or not the name was provided".Instead, insert the "name":