Connect PHP with Java

3

I am making an application, I have a database in Hostinger already created and the PHP files also connected so that I can take the corresponding columns. My problem is that I do not know how to connect these PHP with Java . How do I make the connection? What I want is to simply show the query, it is a test application.

db_connector.php

<?php
define('DB_USER', "****"); // db user
define('DB_PASSWORD', "****"); // db password (mention your db password here)
define('DB_DATABASE', "****"); // database name
define('DB_SERVER', "mysql.hostinger.es"); // db server?>

db_config.php

<?php

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';
// import database connection variables
require_once __DIR__ . '/db_config.php';

// connecting to db
$db = new DB_CONNECT(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);

// get all columns from Preguntes table
$result = mysqli_query($db->connect(),"SELECT * FROM Preguntes") or        die(mysql_error());

// check for empty result
if (mysqli_num_rows($result) > 0) {
    // looping through all results

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

    while ($row = mysqli_fetch_array($result)) {
        // temp user array
        $test = array();
        $test["ID"] = $row["ID"];
        $test["Pregunta"] = $row["Pregunta"];
        $test["Respostes"] = $row["Respostes"];
        $test["Image"] = $row["Image"];

        // push test into final response array
        array_push($response["test"], $test);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
}   else {
    // query is empty
    $response["success"] = 0;
    $response["message"] = "Query is empty";

    // echo no query JSON
    echo json_encode($response);
}?>

database.php

/**
* A class file to connect to database
*/

require_once 'db_config.php';
class DB_CONNECT {

    // connexion property
    private $con = NULL;
    private $db_server;
    private $db_user;
    private $db_password;
    private $db_database;

    // constructor
    function __construct($db_server, $db_user, $db_password, $db_database) {
        $this->db_server = $db_server;
        $this->db_user = $db_user;
        $this->db_password = $db_password;
        $this->db_database = $db_database;
        // connecting to database
        $this->connect();
    }
    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }
    /**
     * Function to connect with database
     */
    function connect() {
        if($this->con==NULL) {
            // Connecting to mysql database
            $this->con = mysqli_connect($this->db_server, $this->db_user, $this->db_password, $this->db_database) or die(mysqli_connect_error());
        }
        // returing connection cursor
        return $this->con;
    }
    /**
     * Function to close db connection
     */
    function close() {
        if($this->con!=NULL) {
            // closing db connection
            mysqli_close($this->con);
        }
    }
}?>
    
asked by user28288 22.01.2017 в 01:19
source

4 answers

1

I see that your communication interface with the server is through JSON encoded responses, however it would be easier if you implemented at least one simple REST API, you could do something like this:

<?php  
header("Content-Type: application/JSON; charset=utf-8");  
const DB_SERVER = 'localhost';  
const DB_USER = 'user';  
const DB_PASS = 'password';  
const DB_NAME = 'database';  
$db = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

$method = $_SERVER['REQUEST_METHOD'];

switch($method) {  
    case 'GET':  
            // todas tus interacciones basadas en solicitudes normales de tipo GET, por ejemplo:  
            if($_GET['action'] == 'preguntas') {  
                // consulta para devolver todas las preguntas...  
                $consulta = $db-query('SELECT * FROM preguntas');  
                .....  
                // la consulta fue exitosa  
                $db->close();  
                http_response_code(200);  
                print json_encode($consulta, JSON_UNESCAPED_UNICODE);  
            }......  
            break;  
        case 'POST':  
            // ahora acá todas tus acciones para las solicitudes tipo POST  
            break;  
        case 'PUT':  
            // acá todo lo de las consultas tipo PUT  
            break;  
        case 'DELETE':  
            // y acá todo lo de DELETE  
            break;  
        default:  
            // acá lo que pasará si ningún tipo de método concuerda aunque es raro que pase  
            break;  
}

For friendly URLs you can use a .htaccess file so that you can make requests with a URL%% of% so that when making the request http://tu-sitio.com/preguntas/ , GET , POST or PUT to that same URL you can perform different actions related to the questions.
The DELETE should look something like this:

RewriteEngine On  
RewriteRule ^([a-zA-Z_-]*)/$ api.php?action=$1 [L,QSA]  
RewriteRule ^([a-zA-Z_-]*)/([0-9]+) api.php?action=$1&question_id=$2 [L,QSA]

Then from your Android app you could help you from very good libraries for asynchronous queries like .htaccess belonging to Google and it's free, just add the dependency to your gradle:

  

Volley

You can also be of utility compile 'com.mcxiaoke.volley:library:1.0.+' that is used to parse your JSON to different types of Java objects, from Gson to your own custom classes:

  

String

This example can be of your use

With this in your complile 'com.google.code.gson:gson:2.8.0' , Activity , Fragment , or practically anywhere you can make queries to your server with Services although I recommend that you implement it in a Volley so you can access the no need to be passing between activities the instance of Singleton . This you can see how it is done on the web that I left you up.
I also recommend that you use a class only and exclusively to store your constructions for the friendly URLs for your REST API , something like this:

public class Constantes {  
    public static final String URL_PRINCIPAL = "http://tu-sitio.com/";  
    public static final String GET_TODAS_PREGUNTAS = URL_PRINCIPAL + "preguntas/";  
    public static final String POST_RESPUESTAS = URL_PRINCIPAL + "respuestas/";  
}

So it's enough that anywhere in your code you do:

Constantes.GET_TODAS_PREGUNTAS  
    ....  

To refer to the URL formed for the query to your REST API .

    
answered by 14.02.2017 в 06:51
0

The solution in general would be to mount a "service", use PHP or any technology for the backend of what you are setting up. From Android or any other system you can call the service, passing parameters if necessary and you will get the answer.

The simplest thing you can do is a page in PHP that returns in plain text, you call from Android to that page and you process the text. If the text you return is in JSON, you can easily parse it in Java with the Jackson library for example (if instead of JSON you use another solution that is also easily parsable in Java, it is equally useful).

But this would be a simple solution, if you are going to set up something serious, go deep into how to set up web services in PHP to contemplate security details and what you need.

    
answered by 27.01.2017 в 14:48
0

maybe this will help you, take into account that the library is depreciated, also take into account that this should be executed with an asynchronic task.

    //Creamos un ArrayList para enviar los parametros en caso de que existan

    String respuesta="error";
    ArrayList<NameValuePair> postparameters2send = new ArrayList<>();

    postparameters2send.add(new BasicNameValuePair("usuario", username));
    postparameters2send.add(new BasicNameValuePair("password", password));

    //la url de nuestro php
    String URL_connect = "www.mysitioweb.com\acceso.php";

    //realizamos una peticion y como respuesta obtenes un array JSON
    JSONArray jdata = post.getserverdata(postparameters2send, URL_connect);


    //si lo que obtuvimos no es null
    if (jdata != null && jdata.length() > 0) {

        return jdata.toString();

    } else{
        return "error";
     }
    
answered by 22.02.2017 в 19:14
0

It will help Php Java bridge pachage .

    
answered by 15.03.2017 в 09:34