How to fetch parameters from POST call in python web service - php

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.

Related

PHP Queries in Play Framework 1.3.x

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.

Manage empty result query in MySql with PHP for Android HttpUrlConnection

I am working in an Android application that is using an Apache server to recover information from a MySQL database with PHP. I do not know the proper way to manage situations where the request to the database is returning 0 records.
In this case I want to minimize as much as possible the process.
So far I can only figure out two ways:
1.- Return an specific XML format and then it is managed by the client. So when this find a specific tags knows there is not records in the database. I do not like this solution because I would like to catch the issue before I parse the XML. The PHP code for this would be something like this.
<?php
include ("common_function.php");
include("generate_DOM_XML.php");
//Make database connection
connectDB();
//set el cotejamiento
mysqli_query($mysqli,"SET NAME 'utf8'");
//sentence sql
$list_news_sql="SELECT new_title, new_body, new_create_time FROM table_news ORDER BY new_create_time DESC";
//results sql query
$list_news_sql_result = mysqli_query($mysqli, $list_news_sql) or die (mysqli_error($mysqli));
if(mysqli_num_rows($list_news_sql_result) < 1){
$message = "<empty>No records</empty>;
echo $message;
}else{
//First parmenter MUST be send AFTER the request is done
$xml_output = mysql_XML($mysqli,$list_news_sql_result,"news","new");
mysqli_free_result($list_news_sql_result);
closeDB();
echo $xml_output;
}
?>
2- Force the server to send an error message and ctach up it before I parse the xml. To make it I do not know if it is possible to use exit(400) or something like that and the capture the message in the client with HttpUrlConnection.getResponseCode() using a sentence if()....else and take a decission before I start the parsing process

connecting to a database using HostMonster

I'm using HostMonster as my web host and I'm trying connect to a database I created using MySQL inside of HostMonster. In order to call that database in my website do I need to use PHP? Or is there a way to create a javascript OnClick function that can call the database. I'm not using ASP.Net so it's not quite as simple as I would like it. Just curious if the best solution is PHP, if so I guess I should go learn it.
what are you planning to do with the database, other than just 'calling it'? You will need some language like PHP to connect to the DB to retrieve, insert, update or delete data in the DB.
here is a code for connection MySQL from PHP using MYSQLI extension
<?php
$dba_host='localhost';
$dba_name='root';
$dba_pass='';
$dba_db='sn';
$con=mysqli_connect($dba_host,$dba_name,$dba_pass,$dba_db) or die('Connection Refused !');
$stmt=mysqli_prepare($con,"SELECT UID FROM Main");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $value);
while(mysqli_stmt_fetch($stmt))
$result[] = $value;
mysqli_stmt_close($stmt);
mysqli_close($con);
?>
Your javascript onClick function is running on the client side (in the browser) and the database is running on the server-side. You will need a server-side language to get the information from the database and send it to the browser.
You do not HAVE to use PHP to connect to a MYSQL database. Also, you can't connect to your database using only client-side javascript (ie. an onClick() function). You need to use a server side language, PHP is one choice.
To connect to a MYSQL database on hostmonster using PHP you will need to know your credentials that use to log into phpMyAdmin from your cpanel. Once you have made the connection you can then select the MYSQL database that you created. Once the database is selected you can query it using the "mysql_query" function in PHP. The following code does all of that and stores the results of the MYSQL query in a PHP variable called $result.
<?php
$con = mysql_connect("www.yourdomain.com","phpMyAdmin_username","phpMyAdmin_password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql_database_name", $con);
$query = "SELECT * FROM TableName"
$result = mysql_query($query);
?>
Now you've got the results of the query inside the PHP variable $result and you can use it anyway you like.
If you put this in your 'public_html' folder and named it 'index.php' or 'index.html' this would automatically be run when someone went to www.yourdomain.com.
You can find a great tutorial series on PHP here http://thenewboston.org/list.php?cat=11.

How to hide SQL queries from web browsers (PHP)

I'm new to this forum and have a dilemma with my MySQL/PHP site. Now I've created a function that will pass a SQL query to it and execute it. What I didn't account for was the fact my SQL query being passed to the function is showing up in the "view source" of all browsers; which is BIG security concern because hackers can see the query. Here is a snippet of the function:
// connect to MySQL
$connection = mysql_connect($host,$username,$password) or die("Couldn't connect to MySQL". mysql_error());
// selects the database
$db = #mysql_select_db($db_name,$connection) or die("Couldn't select database");
function statement ($query)
{
global $connection, $db;
$sql = $query;
$results = mysql_query($sql, $connection) or die(mysql_error());
return $results;
}
Here's how its called:
$cat_results = statement("select * from $category");
Is there a way to hide the query passed from the browser using the function I have? If not any recommendations on a better approach to this function?
Really appreciate any thoughts on this!!
Andre
First of all PHP isn't viewable by the client, it is always executed by the server. Second of all at no point can the client execute SQL on your server. This is the basis of SQL Injection. If you are building a query with JavaScript and then sending it a php script to be executed then you have a very serious vulnerability on your hands.
it is not recommended to pass the query string all the way to the browser/client. you should only pass the query outcome to the client.
Unless you disable PHP on your server, or something breaks, your users won't ever see your PHP code.
PHP code should never show up in the html source. When things are working properly it should all be processed by the server and only the results sent to the client. Maybe you've missed a <? or ?> tag somewhere that's preventing it from being seen as php?

Updating MySQL using SESSION variables via a jquery javascript function

I currently have a javascript file 'score.js' which makes use of jQuery.js, which is being called correctly via a link. The code in score.js is:
function originalUpdateScore(answer,correct){
if (answer == correct)
{
$.post('updateScore.php');
}
window.location.reload(true);
}
This function calls 'updateScore.php':
<?php
include("dbstuff.inc");
$con = mysqli_connect($host, $user, $passwd, $dbname)
or die ("Query died: connection");
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='$_SESSION[logname]')";
mysqli_query($con, $updateScore);
?>
However the database is not being updated correctly. If I replace the line:
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='$_SESSION[logname]')";
with:
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='123pf')";
Where 123pf is the value that the SESSION variable contains in the php file calling the javascript it updates correctly. Why does using the session variable not work? Am I calling it incorrectly in the query?
Thanks in advance.
Are you calling session_start anywhere inside updateScore.php?
If you haven't started the session I do not believe that session variables will be available.
also, do you have complete control over $_SESSION['logname']? If not, someone could easily change their logname to inject SQL and damage/compromise your database. For example, if they were able to set their logname to be this, you could lose your user table:
$_SESSION['logname']="'; DROP TABLE user;-- ";
You're opening yourself right up to cheaters by playing like this. Under this scenario, any user could visit updateScore.php at any time to increase their stats, since that script neither checks their answer nor checks for a token that the JS builds to say the score is ok. It is a bad idea to keep this kind of logic on the front-end (javascript) without also having it verified on the back end (PHP); javascript & AJAX are very helpful shortcuts that can improve user experience, but they cannot be trusted as sole validity checkers.
It's probably just a transcription error, but the code that you have shown in your question uses $_SESSION[logname], it should be $_SESSION['logname'].

Categories