I have successfully connected my android app to a mysql database and did a read from the database which is displaying all the rows from a table in the app. I want to narrow this down so it only displays the rows which correspond with the users id. I have the usersID stored as a shared preference from when they log into the app. I need my php file to recognise the users id and then use this id as part of the query so it only displays the appropriate rows.I am having trouble trying to set this code up and would benefit from some help. Please see the php and java below.
PHP CODE:
<?php
include('conn.php');
if(isset($_GET['userId'])){//The PHP file doesnt work with these two lines
$getId = $_GET['userId'];
$query = "SELECT * FROM Cbt WHERE userId = '$getId'";
$result = mysqli_query($conn, $query);
$json_array = array();
while ($row = mysqli_fetch_assoc($result)){
$json_array[] =$row;
}
}
echo json_encode($json_array);
JAVA CODE:
loginPref = getSharedPreferences("loginPref", Context.MODE_PRIVATE);
final int userId = loginPref.getInt("userId", 0);
textViewResult = findViewById(R.id.text_viewer_result);
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
Api api = retrofit.create(Api.class);
Call<List<WorkoutLogRecycler>> call = api.getLogs();
call.enqueue(new Callback<List<WorkoutLogRecycler>>() {
@Override
public void onResponse(Call<List<WorkoutLogRecycler>> call, Response<List<WorkoutLogRecycler>> response) {
if (!response.isSuccessful()) {
textViewResult.setText("Code:"+response.code());
return;
}
List<WorkoutLogRecycler> workoutLogRecyclers = response.body();
for (WorkoutLogRecycler workoutLogRecycler : workoutLogRecyclers){
String content ="";
content += "cbtId: " + workoutLogRecycler.getCbtId() +"
";
content += "userId: " + workoutLogRecycler.getUserId() +"
";
content += "moodBefore: " + workoutLogRecycler.getMoodBefore() +"
";
content += "automaticThought: " + workoutLogRecycler.getAutomaticThought() +"
";
content += "distortions: " + workoutLogRecycler.getDistortions() +"
";
content += "challengeTought: " + workoutLogRecycler.getChallengeThought() +"
";
content += "alternativeThought: " + workoutLogRecycler.getAlternativeThought() +"
";
content += "moodAfter: " + workoutLogRecycler.getMoodAfter() +"
";
textViewResult.append(content);
}
}
@Override
public void onFailure(Call<List<WorkoutLogRecycler>> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
API CODE:
public interface Api {
@FormUrlEncoded
@POST("insert.php")
Call<ResponseBody> insertLog(
@Field("userId") int userId,
@Field("moodBefore") int moodBefore,
@Field("automaticThought") String automaticThought,
@Field("distortions") int distortions,
@Field("challengeThought") String challengeThought,
@Field("alternativeThought") String alternativeThought,
@Field("moodAfter") int moodAfter
);
@GET("read.php")
Call<List<WorkoutLogRecycler>> getLogs();