I'd like to know if I can use PHP in order to get data from a MySQL database. A fraction of the code can be seen here:
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT aa, bb, cc FROM data";
$result = $conn->query($sql);
...
?>
This is placed inside an HTML file in the Play Framework folder "views", and is properly loaded by the controller, but when it loads, it just shows me the code as if it were text, and not code or the action that would be supposed to do, so it is like it does not recognise it. How can I solve it?
No, you cannot use PHP inside templates, Play doesn't parse PHP at all, actually it doesn't even know there is something like PHP.
P.S. Trying to reuse PHP code in your Java app will be much more difficult than learning the valid approach with Java only, see answer for similar post (it's about MySQL raw access, not PHP integration) which you can reuse in several minutes: https://stackoverflow.com/a/31118795/1066240
As bjfletcher mentioned you would need to configure both runtimes to be able work with Java and PHP at one server but it will NOT allow you for using PHP in Play's templates anyway! so it doesn't make deeper sense.
Play doesn't know PHP.
You need two runtimes:
and use HTTP for integration. For example, if PHP code is on http://localhost/products
then Play would send a GET
request to this URL for a response. Play can then use this response to do whatever you want.
For example:
def index() = Action {
WS.get("http://localhost/products").get.map { resp =>
Ok(views.html.index(resp.body))
}
}
then in your view template:
@(resp: String)
<h1>Products</h1>
@resp
Best thing to do is write it totally in php. Forget about using the bloated playframework and trying to figure out all the connections that you would have to make to tie it all together.