- Live Fast — Code Young
- Using JDBC Java string, to connect to mysql database in PHP
- Using JDBC Java string, to connect to mysql database in PHP
- Connecting MySQL with Java via phpMyAdmin
- JDBC (Java Database Connectivity) Demo using MySQL Phpmyadmin
- PHP With MySQL Tutorial For Beginners
- Connecting to MySQL from Java using PHP
- PHP MySQL Create Database
- PHP MySQLi Create Database Example
- Java Connect to MySQL via PHP-Script
Live Fast — Code Young
In a project I’ve been working on recently we needed to integrate a functionality we have in a few Java classes we developed in to a PHP script. If those specific classes could be wrapped in a simple command-line app, it would not have been a problem, as you can execute command-line apps from PHP easily. But! These specific Java classes took very long time to load (around two seconds!) before they could be used. So command-line app was out of question, because two seconds delays for every command-line execution are unacceptable when dealing with thousands of calls a day, so the solution was to load the app once and to use the already running application when needed.
How do you use a running Java application from PHP code? A quick (and dirty?) solution is sockets. In this case the Java app is the server and PHP is the client. Ok, lets take a look at some code (Links to the sources are at the bottom of the page).
The Java server class looks like this:
public class MyJavaServer public static void main(String[] args) int port = 20222;
ServerSocket listenSock = null; //the listening server socket
Socket sock = null; //the socket that will actually be used for communication
try
listenSock = new ServerSocket(port);
while (true) //we want the server to run till the end of times
sock = listenSock.accept(); //will block until connection recieved
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
String line = "";
while ((line = br.readLine()) != null) bw.write("PHP said: " + line + "\n");
bw.flush();
>
//Closing streams and the current socket (not the listening socket!)
bw.close();
br.close();
sock.close();
>
> catch (IOException ex) ex.printStackTrace();
>
>
>
What it does:
Opens a listening (server) socket which waits for incoming connections on port 20222 in an endless loop. As soon as a connection is received the socket’s input and output streams are «turned» in to buffered reader and writer (so they can be manipulated in an easier and more effective way).
Afterward we read line by line the incoming message, add a «PHP said: » prefix to each line we received and then send it back to the client. After the incoming message is over we close the buffered reader, writer and the socket, and wait for another incoming connection.
Note: It’s important that you add a end-of-line char («\n») to the end of the reply when you are writing to the socket, as the PHP client finishes reading when it encounters the end-of-line char.
The PHP client looks like this:
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->$PORT = 20222; //the port on which we are connecting to the "remote" machine
$HOST = "localhost"; //the ip of the remote machine (in this case it's the same machine)
$sock = socket_create(AF_INET, SOCK_STREAM, 0) //Creating a TCP socket
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT) //Connecting to to server using that socket
or die("error: could not connect to host\n");
$text = "Hello, Java!"; //the text we want to send to the server
socket_write($sock, $text . "\n", strlen($text) + 1) //Writing the text to the socket
or die("error: failed to write to socket\n");
$reply = socket_read($sock, 10000, PHP_NORMAL_READ) //Reading the reply from socket
or die("error: failed to read from socket\n");
echo $reply;
What it does:
We define a port (20222 — the port that MyJavaServer listens on) and a host we want to connect to (localhost is our own machine, change to a specific IP to connect remote machines). Create a socket descriptor ($sock), and connect the socket to the «remote» host (the $succ variable is used to check if the connection was successful). Afterward we write the contents $text to the socket, and then read the server’s reply. The PHP_NORMAL_READ flag tells the socket_read() function to read until the first end-of-line char.
Notes:
* Make sure you add an end-of-line («\n») to the string you send to the server, as the server reads until it encounters the end-of-line char.
* Don’t forget to add 1 to the length of the string you are sending so that the added end of line will actually be sent.
Conclusion:
There’s nothing new in this code neither for «Javers» nor PHPers. The novelty here (for me anywayz) is the interaction between the codes, which on the other makes perfect sense because of the fact that sockets on both utilize the same protocol — in this case TCP/IP.
If you still have questions please ask! If you have comments, well, comment 😀
Using JDBC Java string, to connect to mysql database in PHP
Question: I’m having a weird problem of connection between Java, PHP and MySQL. As im only able to use the DB from my Webhoster through a PHP-Script im wondering how im making the connection to the script workable PHP: Currently im making DB-Connections with Java like this (using H2): After some more research i found that code: After executing i get the following response with the php-Code from above in the Eclipse Console: May someone be able to tell me what is going on and how to get it to work?
Using JDBC Java string, to connect to mysql database in PHP
what i have is java application, that connects to the database. I have username, password and connection url string. Url string is like:
jdbc:mysql://example.ddns.net:3306/something?useSSL=false
Is there a way to use this in order to connect to this mysql database in php? Using something like mysqli?
$conn = new mysqli($servername, $username, $password);
you can find you answer on:
https://www.w3schools.com/php/php_mysql_connect.asp connect_error) < die("Connection failed: " . $conn->connect_error); > echo "Connected successfully"; ?>
Java Tutorial 20 : Connect to MySQL Database, Please Rate, Comment and Subscribe.http://creativitytuts.org. Duration: 15:48
Connecting MySQL with Java via phpMyAdmin
JDBC (Java Database Connectivity) Demo using MySQL Phpmyadmin
In this lecture we will understand 1. What is JDBC?2. Introduction to Databasemanagement Duration: 42:22
PHP With MySQL Tutorial For Beginners
This video on PHP with MySQL tutorial will help you learn all thehow ton create a webpage and Duration: 22:53
Connecting to MySQL from Java using PHP
I’m having a weird problem of connection between Java, PHP and MySQL.
I’m not having direct access to my mySQL database on the webserver through Java. So, I converted the mechanism to run a PHP script, which does the job for me and return the results to my Java Application.
It’s working pretty fine for most of the queries. But I’m not getting expected results when the queries include character fields in the query.
I include the PHP and java code snippets for reference.
Please find me the thing, where I’m doing wrong.
echo"\n"; > > >else < echo " MySQL connect failed ! \n"; >>else < echo " No Query ! \n"; >exit(); // exit without auto_append_file ?>
import javax.swing.*; import java.awt.*; import java.io.*; import java.net.*; import java.applet.*; import java.security.*; public class MySQL_POST < public static void main(String r[])< HttpURLConnection conn=null; try< URL url=new URL("mywebsite.com/postdb.php"); String agent="Applet"; String query="query=" + r[0]; String type="application/x-www-form-urlencoded"; conn=(HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty( "User-Agent", agent ); conn.setRequestProperty( "Content-Type", type ); conn.setRequestProperty( "Content-Length", ""+query.length()); OutputStream out=conn.getOutputStream(); out.write(query.getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while((inputLine=in.readLine())!=null)< System.out.print(inputLine+"\n"); >; in.close(); int rc = conn.getResponseCode(); System.out.print("Response Code = "+rc+"\n"); String rm=conn.getResponseMessage(); System.out.print("Response Message = "+rm+"\n"); >catch(Exception e)< e.printStackTrace(); >finally < conn.disconnect(); >> >
I Have a table named TEST, with fields SID INT(3), SNAME VARCHAR(20), SLNAME VARCHAR(20)
It has got two entries in the table.
When I execute the following queries using Java, I get different types of outputs as follows.
> java MYSQL_POST "SELECT * FROM TEST" Query = SELECT * FROM TEST 1 Test1 Test1L 2 Test2 Test2L Response Code = 200 Response Message = OK
> java MYSQL_POST "SELECT SNAME FROM TEST WHERE SID = 1" Query = SELECT SNAME FROM TEST WHERE SID = 1 Test1 Response Code = 200 Response Message = OK
Which is also as I expected.
> java MYSQL_POST "SELECT SID FROM TEST WHERE SNAME = 'Test1'" Query = SELECT SID FROM TEST WHERE SNAME = \'Test1\' Response Code = 200 Response Message = OK
Which doesn’t result in any result, which as expected should be 1
The queries, which involve characters like SNAME = ‘Test1’ or any other or not working. Except these queries, others are fine.
Please anyone help me in fixing this.
The server running your PHP script has the magic quotes setting on. This automatically escapes quotes in incoming data from POST/GET/etc with backslashes. Using magic quotes is not recommended and they have been deprecated since PHP 5.4.0. Disable them and add proper sanitation to your code — it’s a huge security risk to execute queries straight from external input.
PHP Database connection, Start XAMPP server by starting Apache and MySQL. · Write PHP script for connecting to XAMPP. · Run it in the local browser. · Database is
PHP MySQL Create Database
Since PHP 4.3, mysql_create_db() function is deprecated . Now it is recommended to use one of the 2 alternatives.
PHP MySQLi Create Database Example
'; $sql = 'CREATE Database mydb'; if(mysqli_query( $conn,$sql))< echo "Database mydb created successfully."; >else < echo "Sorry, database creation failed ".mysqli_error($conn); >mysqli_close($conn); ?>
Connected successfully Database mydb created successfully.
JDBC (Java Database Connectivity) Demo using MySQL Phpmyadmin, In this lecture we will understand 1. What is JDBC?2. Introduction to Databasemanagement Duration: 42:22
Java Connect to MySQL via PHP-Script
As im only able to use the DB from my Webhoster through a PHP-Script im wondering how im making the connection to the script workable
Currently im making DB-Connections with Java like this (using H2):
Connection conn = null; String db = "~/testDB"; String dbUser = "user"; String dbPass = "password"; Class.forName("org.h2.Driver"); conn = DriverManager.getConnection("jdbc:h2:tcp://"+h2IP+"/" + db, dbUser, dbPass);
After some more research i found that code:
HttpURLConnection conn=null; try< URL url=new URL("http://www.example.net/database.php"); String agent="Applet"; String query="query=" + "create table test(name varchar(255), id int);"; String type="application/x-www-form-urlencoded"; conn=(HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty( "User-Agent", agent ); conn.setRequestProperty( "Content-Type", type ); conn.setRequestProperty( "Content-Length", ""+query.length()); OutputStream out=conn.getOutputStream(); out.write(query.getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while((inputLine=in.readLine())!=null)< System.out.print(inputLine+"\n"); >; in.close(); int rc = conn.getResponseCode(); System.out.print("Response Code = "+rc+"\n"); String rm=conn.getResponseMessage(); System.out.print("Response Message = "+rm+"\n"); >catch(Exception e)< e.printStackTrace(); >finally
After executing i get the following response with the php-Code from above in the Eclipse Console:
Query = No Query ! Response Code = 200 Response Message = OK
May someone be able to tell me what is going on and how to get it to work?
I had the same situation some time ago. The web hoster didn’t allow direct access to the MySQL database, but allowed for PHP scripts.
Have a look at MySQLTunnel. It’s not JDBC, but HTTP(S) taking the query as URL-encoded «query» parameter and giving the results as JSON. So with the appropriate glue code you can use it instead of a normal JDBC connection.
But before you go that route, be sure to understand the security issues raised by that approach. You don’t want the bad guys to get read and write access to your data, do you?
Java Database Connectivity with MySQL, Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the