How to call R script from PHP? - php

I have a bunch of R scripts that do some calculations and return a result. I am planning of building a PHP website that the user can actually submit a form where the data gets passed to my R script, processed and then return the result to the PHP and update the interface.
The plan is to have a database so when a user submits a form, the data gets stored in the database so R can read, process the input and then insert the result in the database so PHP can grab it. However, there are 2 problems:
How do my R script knows that certain values have been stored in the database so it can grab those values and do the processing?
When my R script finishes processing the data and insert it to mysql db, how do I get PHP to understand that at this moment PHP needs to query the database and grab the value?
Let's say my R script is like the following:
range<-1:20
m<-mean(range)
s<-sum(range)
print(m)
print(s)
As you can see the input at this case would be 1 and 20 to define the range, and the output is to show the values of m and s on my webpage.
Any idea how to accomplish that?
thanks!

shell_exec() or exec() are likely your best choices in PHP. This answer explains the difference.
echo shell_exec("Rscript my_script.R {$_GET['range']}");

I'm no r expert, but it's been done :
/ poorman.php
echo "
";
echo "Number values to generate:
";
echo "Submit";
echo ""
;
if(isset($_GET['N']))
{
$N = $_GET['N'];
// execute R script from shell
// this will save a plot at temp.png to the filesystem
exec("Rscript my_rscript.R $N");
// return image tag
$nocache = rand();
echo("");
}
?>
and the R script…
my_rscript.R
args <- commandArgs(TRUE)
N <- args[1]
x <- rnorm(N,0,1)
png(filename="temp.png", width=500, height=500)
hist(x, col="lightblue")
dev.off()
source

Related

Php ampersand seems not the same as mysql ampersand

Mysql query is
SELECT `IdDP`, `DescriptionOrName` FROM `table` WHERE `DescriptionOrName` = ?;
Instead of ? i use php value, received from another file (with ajax send value to current php file). If in Google Chrome click inspect, then i see such value gr art & print. And this value with ajax send to php file. But i get nothing from mysql.
If i use this
SELECT `IdDP`, `DescriptionOrName` FROM `table` WHERE `DescriptionOrName` = "gr art & print";
then all works.
All works also if i manually type gr art & print as php variable.
Compared from mysql selected gr art & print with php variable (received with ajax). Like
if( trim($val_select_ids_for_clicked_name['DescriptionOrName']) == trim(str_replace("&","&",$_POST['data_to_send']['clicked_name'])) ){
echo 'mysql == to php<br/>';
}
else{
echo 'mysql != to php<br/>';
}
And result is that mysql != to php
Seems finally found solution. For ? must use php like str_replace("&","&",trim($_POST['data_to_send']['clicked_name'])). In other words to replace & with &.
So does it mean that ajax (jquery) takes html value of & (html value is &) and sends & to php....? Are there more characters like this?

Using data passed to PHP via .load() to execute database query

I am trying to get an AJAX query to work. Im passing data to a PHP script using:
$(".example").click(function(){
x = this.innerHTML;
$("#example").load("ajax.php",{"data":x});
});
If ajax.php just includes the following (did this as a test), everything is fine; I've passed JS data successfully to PHP.
echo $_POST['data'];
My goal is to query my DB using $_POST['data'] though. As another test, I made sure the DB connection was all ok. The following works:
$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=?");
$example->bind_param('s',$_SESSION['user_id']);
$example->execute();
$example->bind_result($x,$y,$z,$a);
while($example->fetch()){
echo '<h3>'.$x.'</h3>';
echo '<p>'.$y.'</p>';
echo '<p>'.$z.'</p>';
echo '<p>'.$a.'</p>';
}
When I amend the below lines however, nothing is returned from the script.
$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=? AND a=?");
$example->bind_param('ss',$_SESSION['user_id'],$_POST['data']);
The puzzling thing is that the data being passed from JS initially was obtained from the database. When I use alerts, the words are exactly the same as my my DB record.
Any suggestions? Could this be something to do with datatype? do I need to make sure $_POST['data'] is converted to a string somehow?
When I look in firebug, I see the following POST details ('Test Title' is the data used in my query)
Parameters
data Test Title
Source
data=+Test+Title
Do the + signs represent spaces? perhaps I need to trim a space from beginning of data?
This was due to white space. Fixed with the following:
$(".example").click(function(){
y = this.innerHTML;
x = y.trim();
$("#example").load("ajax.php",{"data":x});
});

Scripting mysql for retrieving data in a loop

Background: Non developer with bash shell scripting knowledge needs to query a READ ONLY DB instance and generate data for given variables.
Data in existing file
A1 B1
A2 B2
......
...
....
An Bn
I would like to connect to the mysql database within the bash script and loop through a select statement "n" number of times
select x, y,z from table tablet_vendors where a=A1 and b=B1
except that A1 and B1 need to be passed as parameters first time, A2 and B2 next time and to n in a for loop. I know the shell side of things, but don't know how to integrate both.
Tried something that can define all possible values for "a" at the beginning of the shell script, but it's way too tedious. Any help is appreciated.
I am open to suggestions on using other scripting languages if they are easy to work with mysql and if you can provide some guidance. My searches are pointing to php and python??
Here's a simpler version:
import MySQLdb as mysql
import csv
con = mysql.connect('localhost','user','password','dbname')
cur = con.cursor()
q = "select x, y,z from tablet_vendors where a=%s and b=%s"
with open('somefile.txt') as f:
rows = csv.reader(f,delimiter='\t')
for row in rows:
cur.execute(q,row)
result = cur.fetchone()
while result:
print result
result = cur.fetchone()
Any errors thrown by MySQL will stop execution. You can wrap the cur. lines in a try/except block to be more elegant.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import _mysql, sys
argumentfile = sys.argv[1]
with open(argumentfile) as f:
sqlarguments = f.readlines()
con = None
username, password = 'testuser', 'testpass'
database = 'testdb'
try:
con = _mysql.connect('localhost', username, password, database)
for line in sqlarguments:
con.query("SELECT x, y,z FROM TABLE tablet_vendors WHERE a='%s' and b='%s;'" % line.split('\t'))
result = con.use_result()
print "MySQL data returned: %s" % \
result.fetch_row()[0]
except _mysql.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)
finally:
if con:
con.close()
More info on Python and MySQL: http://zetcode.com/db/mysqlpython/
(Skip to "First example" if you've got the MySQL and everything setup)
Note the retrieval of sqlarguments which is taken from a textfile which is passed as a parameter to the script as the first and only parameter like: python2 script.py sqlfile.txt.
Also note that i assumed that the SQL parameters are delimited by \t (tab) and not spaces, which i then pass in as a='...' and b='...' encapsulated in ' in case of spaces.

GET php data to a commandline prompt

A PHP application on the server is saving a certain document with a sequential number into a MySQL database. How to obtaion that sequential number to a command line prompt that initiates the local doocument scanner?
ex:
c:\myscan ask_for_current_seq_nmbr.pdf
myscan is something written in c that takes care of the PC stuff. Only the name of file is unknown.
Some code (from the query PHP file)
$query = "SELECT last_seq FROM seq_table WHERE cat = 1";
$result = mysql_query($query, $link) or die('ERROR: '. mysql_error().'<br />ON LINE: '.__LINE__);
while($row = mysql_fetch_assoc($result)) {
echo $row['last_seq'];
}
!!! NOTE !!!
I am fetching a page from a remote server. ex. www.site.com/query.php?q=SELECT * FROM...
And that selection results in the last used sequential number which I would like to use in my command prompt.
!! UPDATE !!
We HAVE to go through a PHP file on the remote server to avoid having to use Remoote MySQL which has to be enabled on an IP basis.
You can call processes that run on the commandline with various function from PHP from the exec familyDocs.
If you're having problems building the actual command string, you can do with:
$cmd = sprintf('c:\myscan %d.pdf', $sequential_number);
As you write that the script is already writing it into the db with the $sequential_number I assume you have it already.
In case the database generates the number, then probably as the primary key. See mysql_insert_idDocs for obtaining the id.
Okay judging by the backslash and the C:\ I am guess you're using windows.
You are going to have to combine the following:
http://dev.mysql.com/doc/refman/5.5/en/mysql.html
How to store the result of a command expression in a variable using bat scripts?
and then to access the content of the variable you created use the %VARIABLE_NAME% syntax.
You should have flag in your mysql table like is_processed with value = 0 or 1.
When scan starts it runs query:
SELECT * FROM TABLE where is_processed = 0 order by sec_number
After processing you should run query:
UPDATE TABLE set is_processed = 1 where sec_number = 'sec_processed_number';

Real time graphing with flot, mysql, php

I'm trying to draw a real time graph as my mysql table is constantly being inserted with values, like a moving graph referenced from
http://kalanir.blogspot.com/2009/11/how-to-plot-moving-graphs-using-flot.html
The values actually come from a carbon dioxide sensor which updates the value of the table with co2 values with positions id. I changed her Math.Random to the code below:
<?php $result = mysql_query("SELECT * FROM node1 ORDER BY id DESC LIMIT 1")or die(mysql_error());?>
<?php $row = mysql_fetch_array( $result );?>
var j = "<?php echo $row['co2'];?>";
var next = "<?php echo $row['id'];?>";
for (var i = 0; i < this.xscale - 1; i++)
{
this.array[i] = [i,this.array[i+1][1]]; // (x,y)
}
this.array[this.xscale - 1] = [this.xscale - 1,j];
However, when i run this code, the first value changes, after which it remains constant, even though the last row of the table is being updated.
I heard it is because in php, the server is only polled once. Therefore i only get a constant reading of the first data. Is there any way in which i can make the graph update to the last value of the table? with ajax?
Thanks for your help
Yes, you can use Periodic refresh (Polling)
or
HTTP Streaming.
Note that both of these options can be quite bandwidth demanding.
you have to do some sort of polling. But even before you do that,
1. create a php file that retrieves all the important data from the db.
2. let that file echo/return that data in a formatted way.
3. have js function poll that file at intervals (a function that runs in setInterval() )
and yes.. there would be some bandwith issues but i think its manageable.

Categories