PHP Queries in Play Framework 1.3.x - php

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:
Play runtime
PHP runtime
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.

Related

How to fetch parameters from POST call in python web service

I am a python developer who is completely new to web development. I wish to develop a web service in python which authenticates user and returns a token.
I was able to do that using PHP (thanks to all the blogs available online). But soon realized that I want to do that in python.
Where I am stuck is that-
I don't understand how to fetch the parameters from POST request, like I was fetching in PHP (see code).
How to return a string or code (in PHP it's echo, should I user return?)
// include db connect class
require_once('veggieking_connect.php');
// connecting to db
$db = new VEGGIEKING_CONNECT();
// set mysql_query for utf8
mysql_query ("set character_set_results='utf8'");
$emp_id = $_POST["mEmpID"];
$emp_pwd = $_POST["mPassword"];
$result = mysql_query("select * from empdata where emp_id like '$emp_id' and emp_pwd like '$emp_pwd'") or die(mysql_error());
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
echo $row['emp_email'];
}
}
else {
echo "Fail";
}
?>
Just like in PHP, emp_id and emp_pwd are fetched, how to do that in python web serice when I call using the same POST request in android.
I understand it's a simple question, but I can't find any good python web services examples which explains what's happening in the code. If you are aware of where I can learn these, please share the url's also, it would be really helpful.
Thanks.
From your php code i understand bit that you want to retrieve and then fetch data in database. For this purpose in python use "psycopg2" module.
psycopg2 python Documentation
Using this Module you can do any operations related to database from python code.
I hope this will help you.

Fatal error: Call to a member function query() on a non-object Error

I have a small problem. I'm trying to make a simple register/login system with sessions and I got this error:
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\members\includes\login.inc.php on line 9
This is the relevant line of code:
$result = $conn->query($sql);
The first time I tried it was working.
The rest of the code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$email = $_POST['email'];
$password = md5($_POST['password']);
$sql = "SELECT email, password FROM member WHERE email = '$email' AND password = '$password'";
$result = $conn->query($sql);
I also have db.php, which is used to connect the MYSQL and everything inside it is fine.
I cannot understand why, the first time I tried it was working I guess and now this kind of error.
I'm also having the db.php which is used to connect the MYSQL and everything inside is fine.. could someone explain me why I keep facing this error ?
I'm going to speculate. I'm speculating that you have a separate file (probably called db.php) which "handles" the setting up of the database connection. I'm further going to speculate that you've a chain of files which are require() (or include())'d into your web app.
I've seen this more times than I care to recall. It's a very old fashioned way of separating code into logical chunks inside PHP - which needs to be left in the past.
I'm speculating that you were previously defining $conn in another script which was included (or required) before this code. A global variable, which had was dependency later in the code execution. Invisible to the file it was declared in.
That's the problem. The quick/hack fix is to rename $conn or the restore the original declaration of it and make sure it's global and make sure it is included before this code is ran.
The proper fix (IMHO) is to look at using a framework (Laravel, Lumen, CodeIgniter, Yii, there are many - take your pick) and read up on the topics of dependency injection, autoloading and namespacing. Think about why global variable declarations make for unmaintainable code.
If you're really reluctant to go with a full framework, at the very least have a look at some database-abstraction libraries like doctrine (and it's sub-library dbal) which can easily be auto-loaded into your project via composer.
As Sascha already pointed out, $conn might be either not defined at all, or it's not an object (hence the error message).
From the code sample you have provided, it's actually a bit hard to tell what kind of connection object you might be using, but I think it's save to say that in your case it might be either PDO or mysqli.
For the sake of simplicity, let's stick with mysqli. A working code sample based on mysqli would look like this (shortened example taken from the docs cited above):
$conn = new mysqli("localhost", "my_user", "my_password", "world");
$result = $conn->query($sql);
Though you really should go for so-called prepared statements, as your code right now is prone to SQL injection as wally already stated.
I would have linked wally's answer and provide you with a link to the PHP docs relating to prepared statements, but apparently, my lack of reputation points don't allow me to, so just do a quick Google search for PHP & prepared statements.
The database connection file has to be added at the beginning of the file.
The present format is easy.
<?php $mysqli = new mysqli("localhost", "Userid", "password", "database name"); if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; }
?>
At the beginningļ¼š
require 'db.php';
$conn = new db();

Is the correct way to connect my website to my server?

I'm a total beginner when it comes to PHP, I have a fair grasp of the syntax but I'm not sure about the safest way to utilise it to connect to my server. I apologise that this is a sort of generic question rather than a code problem, since my code technically works.
I have a .php site doc with a basic comment submission form. The only way I can think of to connect to the server is to allow a "dummy" user with select only privelege to call a stored function to accept the comment.
If my dummy account is called siteuser then am I going round this the right way? This is the section of the PHP that I'm using to connect. I believe this code is only visible server side so nobody can ever see it and use the password or username to connect some other way? Or is there a sort of default string I can use in my php without creating the dummy user, seeing as the php and server is all hosted via the same provider?
$sqlserv = "localhost";
$sqlname = "siteuser";
$sqlpass = "mypassword";
$sqldbdb = "comments_table";
$conn = new mysqli($sqlserv, $sqlname, $sqlpass, $sqldbdb);
What i do is this to connect to my DB
db.php:
<?php
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('/somepath/config.ini');
//Mysqli Connection
$conn = new mysqli($config['host'], $config['user'], $config['pass'], $config['dbname']);
if($conn->connect_errno > 0){
die('Unable to connect to database [' . $conn->connect_error . ']');
//Set encoding
mysqli_set_charset($conn, "utf8") or die;
}
?>
and in config.ini:
[database]
user = johndoe
pass = someweirdpassword
dbname = the_name
host = localhost
both files have 700 permissions, so only user (and no one else can access it)
also the config.ini file is placed somewhere outside the public_html directory, i'm not totally sure if that helps or not but i do it that way.

mysql dies everytime I try to create a new table

I am attempting to create new tables every time I post to this method, but for some reason I can not figure out why it dies.
<?php
$host = "127.0.0.1";
$username = 'cotten3128';
$pwd = 'pwd';
$database = "student_cotten3128";
$pin = $_REQUEST['pinSent'];
$words = $_REQUEST['resultSent'];
$tableName = $pin;
$db = new mysqli($host, $username, $pwd, $database);
if ($sql = $db->prepare("CREATE TABLE $pin (id INT(11) AUTO_INCREMENT);")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die('Could not create table');
}
for($i=0;$i<count($words);$i++){
if($sql = $db->prepare("INSERT INTO ".$pin.$words[$i].";")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die("Could not add data to table");
}
}
mysqli_close();
?>
Any help or insight would be greatly appreciated.
The intention of my post is to help you finding the issue by yourself. As you did not added much information I assume my post is helpful for you.
Based on the code you have shared I guess you mean one of your called die() functions is executed.
Wrong function call
As Jay Blancherd mentioned mysql_close is the wrong function. You rather have to use mysqli_close as you created a mysqli instance.
Beside of that mysql_* is deprecated and should not be used anymore.
Debugging Steps
Not only for this case but in general you should ask yourself:
Is there an error message available? (Frontend output, error log file, ...)
YES:
What's the message about?
Is it an error you can search for? E.g. via a search engine or the corresponding documentation?
Look up in the bug tracker (if available), by the software developer of the software you are using, and if it has not been reported yet report the issue.
NO: (if none error message available OR you cannot search for it as it is a custom error message)
Search in the files of the software you are using for the error message and start a core-debugging.
STILL NO SOLUTION?:
Ask on stackoverflow.com e.g. and tell your issue and the steps you have performed to find and fix the bug. Post only as much code as necessary plus use a proper format.
Debugging in your case:
In order to narrow down the scope. Which of the die() is executed? Depending on that echo the query to execute just before it actually is executed. Then copy the SQL query to an SQL editor and look at it syntax. After that you probably know the problem already.

PHP Page reference check from multiple URLs

I have a php script that limits the amount of times people can download content on my site. I found this script by google searching and changed it a bit to get it working for me.
The problem is I don't know anything really about php. The first part of the script checks the referring page. When I copied the php script, it was set up to check a single URL. My problem is I want to reference the php script from multiple pages, because one page has flash on it, and another page I created for mobile phones that don't have flash. Because of this, the link only works on one page - the page with the url I replace in the script.
My question is, what is the code to include multiple URLs in the reference check? I don't know if it's something very simple, or if it's even possible.
Below is the part of the php script which checks the referring URL, and then proceeds to login to mySQL DB to begin the download.
$referer = $_SERVER['HTTP_REFERER'];
$keymatch= $_SESSION['key'];
$pass='key';
$md5value= md5($pass);
if (($referer=="my url containing php script link")&& ($keymatch==$md5value)) {
$username = "user";
$password = "password";
$hostname = "host";
$database = "database";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database,$dbhandle)
or die("Could not select $database");
Thanks in advance for any help.
-Richard
Rather than checking referer matches on one link:
if (($referer=="my url containing php script link")...
Create an array of links and match against that:
$referers = array('link1', 'link2','link3');
if((in_array($referer, $referers)...

Categories