即使条件为空,也显示联接表结果

时间:2017-11-13 10:21:34

标签: php mysql codeigniter

我有五个表名图书类别出版物作者评论

在我的应用用户可以在登录后查看该书。所以评论表保持空白,直到用户发表评论为止。

我正在尝试在codeigniter模型中运行流动查询以通过category_id获取书籍详细信息,并且当它们的评论存在时它工作正常,否则它将返回空数组。发生这种情况的原因是$this>db>join('reviews','reviews.book_id = books.book_id');条件返回false

我怎样才能显示结果甚至评论表条件不匹配?

public function get_book_details($cat_id) {

        $this->db->select('*');
        $this->db->from('books');
        $this->db->join('categories', 'categories.id = books.category_id');
        $this->db->join('publications', 'publications.id = books.publication_id');
        $this->db->join('author', 'author.id = books.author_id');
        $this->db->join('reviews', 'reviews.book_id = books.book_id');
        $this->db->where('categories.id', $cat_id);

        $query = $this->db->get();
        return $query->result();
    }

1 个答案:

答案 0 :(得分:0)

如果找不到匹配的关联,请使用$this->db->join('reviews', 'reviews.book_id = books.book_id','LEFT'); 获取结果

Img_profile_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (Build.VERSION.SDK_INT >= 23) {
                    // Marshmallow+
                    if (!checkAccessFineLocationPermission() || !checkWriteExternalStoragePermission()) {
                        requestPermission();
                    } else {
                        chooseimage();
                    }
                } else {
                    chooseimage();
                }

            }
        });

    }
   
   


   

   
    private void takePicture() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        camera_FileUri = getOutputMediaFileUri(1);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, camera_FileUri);
        // start the image capture Intent
        startActivityForResult(intent, REQUEST_TAKE_PHOTO);
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, galleryRequestCode);
    }

    /**
     * Creating file uri to store image/video
     */
    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }


    /**
     * returning image / video
     */
    private static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(TAG, "Oops! Failed create "
                        + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == 1) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".jpg");
        } else {
            return null;
        }

        return mediaFile;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on screen orientation
        // changes
        outState.putParcelable("file_uri", camera_FileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        camera_FileUri = savedInstanceState.getParcelable("file_uri");
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_TAKE_PHOTO ||  requestCode == UCrop.REQUEST_CROP) {
                try {
                    if (requestCode == REQUEST_TAKE_PHOTO) {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inSampleSize = 8;

                        final Bitmap bitmap = BitmapFactory.decodeFile(camera_FileUri.getPath(), options);
                        Bitmap thumbnail = bitmap;
                        final String picturePath = camera_FileUri.getPath();
//                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                        File curFile = new File(picturePath);
                        try {
                            ExifInterface exif = new ExifInterface(curFile.getPath());
                            int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                            int rotationInDegrees = exifToDegrees(rotation);

                            Matrix matrix = new Matrix();
                            if (rotation != 0f) {
                                matrix.preRotate(rotationInDegrees);
                            }
                        //    thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
                        } catch (IOException ex) {
                            Log.e("TAG", "Failed to get Exif data", ex);
                        }


                        System.out.println("edit-----" + Iconstant.Edit_profile_image_url);

                        Uri picUri = Uri.fromFile(curFile);

                        UCrop.of(picUri, picUri)
                                .withAspectRatio(4, 4)
                                .withMaxResultSize(8000, 8000)
                                .start(ProfilePage.this);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else if (requestCode == galleryRequestCode) {

                Uri selectedImage = data.getData();
                if (selectedImage.toString().startsWith("content://com.sec.android.gallery3d.provider")) {
                    String[] filePath = {MediaStore.Images.Media.DATA};
                    Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePath[0]);
                    final String picturePath = c.getString(columnIndex);
                    c.close();
                    File curFile = new File(picturePath);

                    Picasso.with(ProfilePage.this).load(picturePath).resize(100, 100).into(new Target() {
                        @Override
                        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                            Bitmap thumbnail = bitmap;
                            mSelectedFilePath = picturePath;
                            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
                        }

                        @Override
                        public void onBitmapFailed(Drawable errorDrawable) {
                        }

                        @Override
                        public void onPrepareLoad(Drawable placeHolderDrawable) {
                        }
                    });

                    Uri picUri = Uri.fromFile(curFile);

                    UCrop.of(picUri, picUri)
                            .withAspectRatio(4, 4)
                            .withMaxResultSize(8000, 8000)
                            .start(ProfilePage.this);

                } else {
                    String[] filePath = {MediaStore.Images.Media.DATA};
                    Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                    c.moveToFirst();

                    int columnIndex = c.getColumnIndex(filePath[0]);
                    final String picturePath = c.getString(columnIndex);
                    Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
                    Bitmap thumbnail = bitmap; //getResizedBitmap(bitmap, 600);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    File curFile = new File(picturePath);

                    try {
                        ExifInterface exif = new ExifInterface(curFile.getPath());
                        int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                        int rotationInDegrees = exifToDegrees(rotation);

                        Matrix matrix = new Matrix();
                        if (rotation != 0f) {
                            matrix.preRotate(rotationInDegrees);
                        }
                        thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
                    } catch (IOException ex) {
                        Log.e("TAG", "Failed to get Exif data", ex);
                    }
                    thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);

                    c.close();
                                        Uri picUri = Uri.fromFile(curFile);

                    UCrop.of(picUri, picUri)
                            .withAspectRatio(4, 4)
                            .withMaxResultSize(8000, 8000)
                            .start(ProfilePage.this);
                                    }
            }


            if ( requestCode == UCrop.REQUEST_CROP) {

                final Uri resultUri = UCrop.getOutput(data);
                try {
                    selectedBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
                byteArray = byteArrayOutputStream.toByteArray();
                Img_profile_pic.setImageBitmap(selectedBitmap);
                Img_profile_pic.setImageURI(resultUri);
                UploadDriverImage(Iconstant.Edit_profile_image_url);

            } else if (resultCode == UCrop.RESULT_ERROR) {
                final Throwable cropError = UCrop.getError(data);
                System.out.println("========muruga cropError==========="+cropError);
            }


        }


    }


    private static int exifToDegrees(int exifOrientation) {
        if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
            return 90;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
            return 180;
        } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
            return 270;
        }
        return 0;
    }

    private void UploadDriverImage(String url) {

        dialog = new Dialog(ProfilePage.this);
        dialog.getWindow();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.custom_loading);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        TextView dialog_title = (TextView) dialog.findViewById(R.id.custom_loading_textview);
        dialog_title.setText(getResources().getString(R.string.action_loading));

        VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
            @Override
            public void onResponse(NetworkResponse response) {

                System.out.println("------------- image response-----------------"+response.data);


                String resultResponse = new String(response.data);
                System.out.println("-------------  response-----------------"+resultResponse);
                String sStatus = "", sResponse = "",SUser_image="",Smsg="";
                try {
                    JSONObject jsonObject = new JSONObject(resultResponse);
                    sStatus = jsonObject.getString("status");
                    if (sStatus.equalsIgnoreCase("1")) {
                //        JSONObject responseObject = jsonObject.getJSONObject("response");
                    //    SUser_image = jsonObject.getString("image");
                        Smsg = jsonObject.getString("image_url");

                 //       Img_profile_pic.setImageBitmap(bitMapThumbnail);
                        session.setuser_image(Smsg);
                        Picasso.with(ProfilePage.this).load(Smsg).placeholder(R.drawable.no_user_image).into(Img_profile_pic);

                        NavigationDrawer.navigationNotifyChange();
                        Locale locale = null;
                        switch (language_code){

                            case "en":
                                locale = new Locale("en");
                                session.setlamguage("en","en");


                                break;
                            case "es":
                                locale = new Locale("es");
                                session.setlamguage("es","es");
                                //      session.setlamguage("Ar",language_change.getSelectedItem().toString());
                                //     System.out.println("========Arabic Language========"+language_change.getSelectedItem().toString()+"\t\tar");
                                //     Intent i=new Intent(ProfilePage.this,NavigationDrawer.class);
                                //     finish();
                                //     startActivity(i);

//                        Intent bii = new Intent();
//                        bii.setAction("homepage");
//                        sendBroadcast(bii);
//                        finish();
                                break;
                            case "ta":
                                locale = new Locale("ta");
                                session.setlamguage("ta","ta");
                                //      session.setlamguage("Ar",language_change.getSelectedItem().toString());
                                //     System.out.println("========Arabic Language========"+language_change.getSelectedItem().toString()+"\t\tar");
                                //     Intent i=new Intent(ProfilePage.this,NavigationDrawer.class);
                                //     finish();
                                //     startActivity(i);

//                        Intent bii = new Intent();
//                        bii.setAction("homepage");
//                        sendBroadcast(bii);
//                        finish();
                                break;
                            default:
                                locale = new Locale("en");
                                session.setlamguage("en","en");
                                break;
                        }

                        Locale.setDefault(locale);
                        Configuration config = new Configuration();
                        config.locale = locale;
                        getApplicationContext().getResources().updateConfiguration(config, getApplicationContext().getResources().getDisplayMetrics());


                        Alert(getResources().getString(R.string.action_success),getResources().getString(R.string.edit_profile_success_label));

                    } else {
                        sResponse = jsonObject.getString("response");
                        Alert(getResources().getString(R.string.my_rides_rating_header_sorry_textview), sResponse);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                catch (Exception e) {
                    Toast.makeText(ProfilePage.this,"Something happened , try again",Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                dialog.dismiss();

                NetworkResponse networkResponse = error.networkResponse;
                String errorMessage = "Unknown error";
                if (networkResponse == null) {
                    if (error.getClass().equals(TimeoutError.class)) {
                        errorMessage = "Request timeout";
                    } else if (error.getClass().equals(NoConnectionError.class)) {
                        errorMessage = "Failed to connect server";
                    }
                } else {
                    String result = new String(networkResponse.data);
                    try {
                        JSONObject response = new JSONObject(result);
                        String status = response.getString("status");
                        String message = response.getString("message");

                        Log.e("Error Status", status);
                        Log.e("Error Message", message);

                        if (networkResponse.statusCode == 404) {
                            errorMessage = "Resource not found";
                        } else if (networkResponse.statusCode == 401) {
                            errorMessage = message + " Please login again";
                        } else if (networkResponse.statusCode == 400) {
                            errorMessage = message + " Check your inputs";
                        } else if (networkResponse.statusCode == 500) {
                            errorMessage = message + " Something is getting wrong";
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                Log.i("Error", errorMessage);
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                System.out.println("------------Authkey------cabily---------" + Agent_Name);
                System.out.println("------------userid----------cabily-----" + UserID);
                System.out.println("------------apptoken----------cabily-----" + gcmID);
                System.out.println("------------applanguage----------cabily-----" + language_code);
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authkey", Agent_Name);
                headers.put("isapplication",Iconstant.cabily_IsApplication);
                headers.put("applanguage",language_code);
                headers.put("apptype", Iconstant.cabily_AppType);
                headers.put("userid",UserID);
                headers.put("apptoken",gcmID);
              /*  System.out.println("servicereques  apptype------------------"+Iconstant.cabily_AppType);
                System.out.println("servicereques apptoken------------------"+gcmID);
                System.out.println("servicereques userid------------------"+UserID);
                Map<String, String> headers = new HashMap<String, String>();

                headers.put("User-agent",Iconstant.cabily_userAgent);
                headers.put("isapplication",Iconstant.cabily_IsApplication);
                headers.put("applanguage",Iconstant.cabily_AppLanguage);
                headers.put("apptype",Iconstant.cabily_AppType);
                headers.put("apptoken",gcmID);
                headers.put("userid",UserID);*/

                return headers;
            }
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("user_id",UserID);
                System.out.println("user_id---------------"+UserID);
                return params;
            }

            @Override
            protected Map<String, DataPart> getByteData() {
                Map<String, DataPart> params = new HashMap<>();
                params.put("user_image",new DataPart("cabily_user.jpg", byteArray));

                System.out.println("user_image--------edit------"+byteArray);

                return params;
            }
        };

        //to avoid repeat request Multiple Time
        DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        multipartRequest.setRetryPolicy(retryPolicy);
        multipartRequest.setRetryPolicy(new DefaultRetryPolicy(60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        multipartRequest.setShouldCache(false);
        AppController.getInstance().addToRequestQueue(multipartRequest);

    }


    // --------------------Method for choose image to edit profileimage--------------------
    private void chooseimage() {
        photo_dialog = new Dialog(ProfilePage.this);
        photo_dialog.getWindow();
        photo_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        photo_dialog.setContentView(R.layout.image_upload_dialog);
        photo_dialog.setCanceledOnTouchOutside(true);
        photo_dialog.getWindow().getAttributes().windowAnimations = R.style.Animations_photo_Picker;
        photo_dialog.show();
        photo_dialog.getWindow().setGravity(Gravity.CENTER);

        RelativeLayout camera = (RelativeLayout) photo_dialog
                .findViewById(R.id.profilelayout_takephotofromcamera);
        RelativeLayout gallery = (RelativeLayout) photo_dialog
                .findViewById(R.id.profilelayout_takephotofromgallery);

        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePicture();
                photo_dialog.dismiss();
            }
        });

        gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
                photo_dialog.dismiss();
            }
        });
    }



    private boolean checkAccessFineLocationPermission() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    private boolean checkAccessCoarseLocationPermission() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    private boolean checkWriteExternalStoragePermission() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED ||  grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
                    chooseimage();
                } else {
                    finish();
                }
                break;
        }
    }