Results 1 to 9 of 9
  1. #1
    bobdole's Avatar
    bobdole is offline Member
    Join Date
    Jun 2013
    Posts
    6
    Rep Power
    0

    Default Using php code in Java?

    I have a website called [Moderator edit: link removed]

    I am trying to make a program that can access the same database from my website and do it through php. Someone told me to use code like this:

    Java Code:
    {
            //This is a single line comment
            /*This is a multiple line comment*/
            HttpURLConnection connection = null;  
            PrintWriter outWriter = null;  
            BufferedReader serverResponse = null;  
            StringBuffer buff = new StringBuffer();  
            try  
            {  
            //OPEN CONNECTION  
            connection = ( HttpURLConnection ) new URL( "http://marveldcforum.com/android/testpage.php" ).openConnection();  
    
            //SET REQUEST INFO  
            connection.setRequestMethod( "POST" );  
            connection.setDoOutput( true );  
    
            //CREATE A WRITER FOR OUTPUT  
            outWriter = new PrintWriter( connection.getOutputStream() );  
    
            //PARAMETERS  
            buff.append( "param1=" );   
            buff.append( URLEncoder.encode( "Param 1 Value", "UTF-8" ) );  
            buff.append( "&" );  
            buff.append( "param2=" );   
            buff.append( URLEncoder.encode( "Param 2 Value", "UTF-8" ) );  
    
            //SEND PARAMETERS  
            outWriter.println( buff.toString() );  
            outWriter.flush();  
            outWriter.close();  
    
            //RESPONSE STREAM  
            serverResponse = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );  
    
            //READ THE RESPOSNE  
            String line;  
            while ( (line = serverResponse.readLine() ) != null )   
            {  
            System.out.println( line );  
            }  
            }  
            catch (MalformedURLException mue)  
            {  
            mue.printStackTrace();  
            }  
            catch (IOException ioe)  
            {  
            ioe.printStackTrace();  
            }  
            finally  
            {  
            if ( connection != null )  
            connection.disconnect();  
    
            if ( serverResponse != null )  
            {  
            try { serverResponse.close(); } catch (Exception ex) {}  
            }  
            }  
    }

    This code simply displays the test page data.

    <html>
    <head>
    </head>

    <body>
    <h2>Test Page</h2>
    Test PHP
    </body>

    </html>


    This isn't what I was looking for. I am trying to actually display the data, such as:

    Test Page
    Test PHP

    like the actual HTML and php data. Not the tags. How can I approach this? I've been googling it forever and I am not sure what to search for. Can anyone point me in the right direction?
    Last edited by DarrylBurke; 06-19-2013 at 05:59 AM. Reason: Removed spammy link

  2. #2
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,049
    Rep Power
    6

    Default Re: Using php code in Java?

    You open an URL connection to a site and what you'll get back is whatever the site produces, which is most likely HTML intended for a browser. If that is not what you want then this code is not ever going to help you.

    Seems to me like you want to write Java code which connects to the database directly and not go through the web. You use the JDBC API for that. But if you must go through the web then think about exposing a RESTful webservice in your PHP site which you can invoke from Java through JAX-RS.

    Both methods will require you to study a lot, its not trivial in the slightest. But that's the life of a programmer, always learning.

  3. #3
    bobdole's Avatar
    bobdole is offline Member
    Join Date
    Jun 2013
    Posts
    6
    Rep Power
    0

    Default Re: Using php code in Java?

    Quote Originally Posted by gimbal2 View Post
    You use the JDBC API for that.
    Thanks! That's exactly what I was looking for. I don't see a need to use the website if it's not needed. I just needed a point in the right direction. I'm currently looking on Java SE Technologies - Database

    For examples of how to connect to a database and display info. If anyone has any starter code they could show me it would really speed it up. Thanks!

  4. #4
    bobdole's Avatar
    bobdole is offline Member
    Join Date
    Jun 2013
    Posts
    6
    Rep Power
    0

    Wink Re: Using php code in Java?

    I've been using this code with my database credentials plugged in.

    PHP Code:
    import java.sql.*;
    
    public class FirstExample {
      // JDBC driver name and database URL
      static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
      static final String DB_URL = "jdbc:mysql://localhost/EMP";
    
      //  Database credentials
      static final String USER = "username";
      static final String PASS = "password";
       
      public static void main(String[] args) {
      Connection conn = null;
      Statement stmt = null;
      try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");
    
      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);
    
      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);
    
      //STEP 5: Extract data from result set
      while(rs.next()){
      //Retrieve by column name
      int id  = rs.getInt("id");
      int age = rs.getInt("age");
      String first = rs.getString("first");
      String last = rs.getString("last");
    
      //Display values
      System.out.print("ID: " + id);
      System.out.print(", Age: " + age);
      System.out.print(", First: " + first);
      System.out.println(", Last: " + last);
      }
      //STEP 6: Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
      }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
      }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
      }finally{
      //finally block used to close resources
      try{
      if(stmt!=null)
      stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
      if(conn!=null)
      conn.close();
      }catch(SQLException se){
      se.printStackTrace();
      }//end finally try
      }//end try
      System.out.println("Goodbye!");
    }//end main
    }//end FirstExample

    I keep getting the error:

    "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"

    Then it says "Goodbye!", which means that the try catch was unsuccessful I assume. I plugged in my info for DB_URL, USER, & PASS. I am familiar with connecting to my database through PHP so it shouldn't be very difficult. I'm just not sure what I need to put in

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

    I'm not familiar with this aspect of Java. Any help would be amazing

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,300
    Rep Power
    20

    Default Re: Using php code in Java?

    Learn to indent code for readability: Code Conventions for the Java Programming Language: Contents

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  6. #6
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,049
    Rep Power
    6

    Default Re: Using php code in Java?

    Sorry, you can't program Java without learning Java. You are apparently blissfully unaware about one of the most important core concepts of the Java platform: the classpath. It is what Java uses to know where to look for classes and libraries. I suggest you research that to the point where you understand how and why it works, then you won't ever have these kind of problems anymore. A google for "java classpath" will likely give you all the information you need, but I do suggest getting a good book about Java anyway.

  7. #7
    bobdole's Avatar
    bobdole is offline Member
    Join Date
    Jun 2013
    Posts
    6
    Rep Power
    0

    Default Re: Using php code in Java?

    Thanks guys. I guess three Java classes in college and a degree aren't what they should be. Having enough drive to go out and learn the rest on my own is obviously a bad idea. I'll only come back after I have complete mastery over the subject and have no need for this forum.

  8. #8
    bobdole's Avatar
    bobdole is offline Member
    Join Date
    Jun 2013
    Posts
    6
    Rep Power
    0

    Default Re: Using php code in Java?

    Quote Originally Posted by DarrylBurke View Post
    Learn to indent code for readability: Code Conventions for the Java Programming Language: Contents

    db
    Sometimes when you copy and paste code in different places the format changes.

  9. #9
    noctarius is offline Member
    Join Date
    Jun 2012
    Location
    Remscheid, Germany
    Posts
    61
    Rep Power
    0

    Default Re: Using php code in Java?

    If you want to use PHP inside of Java (instead of listening to an external process) you could try quercus Caucho Resin : Reliable, Open-Source Application Server

Similar Threads

  1. Compiling another java code from our code
    By madhav.dubey9 in forum New To Java
    Replies: 18
    Last Post: 03-11-2013, 04:54 PM
  2. Replies: 16
    Last Post: 01-31-2012, 08:36 PM
  3. Replies: 0
    Last Post: 02-21-2011, 11:50 AM
  4. Convert java code to midlet code
    By coldvoice05 in forum New To Java
    Replies: 1
    Last Post: 08-12-2009, 11:14 AM
  5. Convert java code to midlet code
    By coldvoice05 in forum Advanced Java
    Replies: 1
    Last Post: 08-09-2009, 01:21 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •