How to access hive data to html page - php

I have some crawled data in hadoop. I have exported data from hbase table to hive table.. So now I have to access its tables via html, php etc. so that I can display it on web. Is their any tutorial or tool available for it. Please guide me thoroughly. My final aim is to search some record from web from hive table.

you can connect Hive with PHP to show the data in webpage.For that you need to use ThrifSQL.phar.
refer the below code
<html>
<body>
<?php
// Load this lib
require_once __DIR__ . '/ThriftSQL.phar';
// Try out a Hive query
$hive = new \ThriftSQL\Hive( 'localhost', 10000, 'user', 'pass' );
$hql = "SELECT * from default.phpexample";
$client = $hive
->connect()
->setSasl(false)
->queryAndFetchAll($hql);
print_r($client);
echo "<table>
<tr>
<th>site_name</th>
<th>price</th>
</tr>";
foreach ($client as $row) {
echo "<tr>\n";
foreach ($row as $field) {
echo "<td>$field</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
$hive->disconnect();
?>
</body>
</html>
Refer https://github.com/Automattic/php-thrift-sql/blob/master/example.php

Related

generate an Excel file using PHP

I'm new with PHP, I'm developping a WEB application that display a table with informations from an SQL server DATA BASE, the problem that I want to add a button to generate an EXCEL file that contains the table displayed? Is that possible??
#Ranjit this is the PHP code that displays the table and generate the excel file
edit 1
<?php
$ch="";
if(isset($_POST['historique']))
{
if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
{
$ch= "(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
?>
<table id="tab" border="1">
<tr>
<th><font color="red">Date</font></th>
<th><font color="red">Agent</font></th>
<th><font color="red">numéro</font></th>
</tr>
<?php
$search = " // my query
where operationDate between" .$ch;
$stmt = mssql_query($search);
while ($data = mssql_fetch_assoc($stmt))
{
?>
<tr>
<td><?php echo utf8_encode ($data['operationDate']);?></td>
<td><?php echo utf8_encode ($data['fullName']);?></td>
<td><?php echo utf8_encode ($data['number']);?></td>
</tr>
<?php
} }
?>
</table>
<?php
}
$output ='';
if(isset($_POST['excel']))
{
if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
{
$rq = "// my query
where operationDate between" ."(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
$res = mssql_query($rq);
if(mssql_num_rows($res)>0)
{
$output.='<table border=1>
<tr>
<th>Date</th>
<th>Depanneur</th>
<th>numéro</th>
</tr>
';
while ($row=mssql_fetch_array($res))
{
$output .='
<tr>
<td>'.$row["operationDate"].'</td>
<td>'.$row["fullName"].'</td>
<td>'.$row["number"].'</td>
</tr>';
}
$output .='</table>';
header("Content-Type: application/xls;charset=UTF-8");
header("Content-Disposition: attachement; filename=file.xls");
echo $output;
//mssql_close($conn);
}}}
?>
You'll have to select the data manually then insert them into the excel sheet, there's php library called PHPEXCEL you can use it.
See this
http://www.c-sharpcorner.com/article/export-to-excel-in-php-with-my-sql/
There are some nice packages out there to generate excel files such as
Box Spout and PHP Spreadsheet.
The documentation of both packages is very clear any you will be generating excel files within minutes of browsing through documentation.
Yes,
It is possible. You can follow this
1) Connect to database:
2) Define a filename of excel
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
$fp = fopen('database.xls', "w");
$schema_insert = "";
$schema_insert_rows = "";
//start of printing column names as names of MySQL fields
Sources - http://www.anillabs.com/2010/03/how-to-create-excel-file-with-mysql-data-using-php-code/

Database path on raspberry

I'm new in raspberry and I'm trying to read a simple database from a php page but there is something wrong: I can't read the database content: Here the php page code:
<!DOCTYPE html>
<html>
<body>
<H1>Test Database</H1>
<?php
$sq = sqlite_open('miodatabase.db', 0666, $sqlite_error);
if(!$sq)
{
die(“Errore Sqlite: “.$sqlite_error);
}
$result = sqlite_query($sq, 'select * from test');
while($data = sqlite_fetch_array($result))
{
echo $data[‘nome’];
}
sqlite_close($sq);
?>
</body>
</html>
The database is "miodatabase" that contains a table called "test". I put the database in \var\www\html folder (is correct?) but when I open the page I see a blank page. I'm sure the database contains the table (tested with sqlite3 commands) and the table contains one row. Where I need to put the database? Why I can't see nothing? Thanks
If you don't see anything, i think it's a php configuration issue.
Did you try to add :
<?php phpinfo(); ?>
at the beginning of your script. If you have blank page, look your apache/nginx configuration.
You can also try to run your script from the command line. Maybe helpful in some case.
UPdate
If you use SQLite3 follow this code
class MyDB extends SQLite3
{
function __construct()
{
$this->open('miodatabase.db');
}
}
$db = new MyDB();
$result = $db->query('select * from test', SQLITE3_OPEN_READWRITE );
//var_dump($result->fetchArray());
while($data = $result->fetchArray())
{
echo $data[‘nome’];
}
$db->close();
I solved: I type again the command
sudo apt-get install php5-sqlite
sudo /etc/init.d/apache2 restart
and then I can see in the php info the sections about sqlite3.
The I update my php page like this:
//Enable show error
ini_set('display_errors', 'On');
error_reporting(E_ALL|E_STRICT);
$db = new SQLite3("miodatabase.db");
$sql_select='SELECT * FROM test';
$result=$db->query($sql_select);
echo "<table border='1'>";
echo "<tr>";
$numColumns=$result->numColumns();
for ($i = 0; $i < $numColumns; $i++)
{
$colname=$result->columnName($i);
echo "<th>$colname</th>";
}
echo "</tr>";
while($row = $result->fetchArray(SQLITE3_NUM))
{
echo "<tr>";
for ($i = 0; $i < $numColumns; $i++)
{
$value=$row[$i];
echo "<th>$value</th>";
}
echo "</tr>";
}
echo "</table>";
To open the database I use now
$db = new SQLite3("miodatabase.db");
because the sqlite_open is not supported by this version of sqlite.
Now all works correctly

How can I add a SQL result of a PHP statement (fromMySQL) in an existing HTML file

I have an html file that contains a table with table rows
<table style="width:auto">
<tr>
<td contenteditable="true"><select id="so"></select></td>
</tr>
</table>
I have a PHP that selects from mySQL DB and returns username
if ($results->num_rows > 0) {
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
echo "<option>
$name
</option>";
}
} else {
echo "0 results";
}
I am trying to incorporate the result of the php into my index.html file within the table so that the option shows up in the table
How can I get the data from PHP into an already built html table row?
Any help would be appreciated.
Two way to get the job done:-
1)Use a class, that is you should, and using its object you can retrieve the data and use it on the webpage .
ex:- see this class, it needs a lot of improvements and changes, but still can give you some idea . I am also trying to learn PDO well, not a PRO, but can be helpful to you.Comments on this class will help you get the idea .
2)Using AJAX, You can request for this data on loading the document or you can request it via get, post, request.. on any event.If you know ajax, you can use that class and ajax, or if you do not have an idea about AJAX, you can get a lot of resources to learn ajax. after this if you need my assistant, I will try to help you.
for this work you should use ajax to load data in html file ...
you can do it with javascript :
create a function for load your php file :
function loadAjax(address,elementId) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(elementId).innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", address, true);
xhttp.send();
}
after create it you can use it when you want (for example after load of page). you should pass address of your php file and id of html element that you want the answer load into it .
for more learn :
http://www.w3schools.com/ajax/
There are couple of methods that can be used here. If the HTML and PHP are in the same file you could do this:
<?php
if ($results->num_rows > 0) {
$options = ''; // declare the variable to hold the options
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
$options .= "<option>$name</option>"; // add the options to the variable
}
} else {
$options = "0 results";
}
?>
And then add the $options to the HTML:
<table style="width:auto">
<tr>
<td contenteditable="true">
<select id="so">
<?php echo $options; ?>
</select>
</td>
</tr>
</table>
Another option, though not as neat, is to embed the PHP in the HTML:
<table style="width:auto">
<tr>
<td contenteditable="true">
<select id="so">
<?php
if ($results->num_rows > 0) {
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
echo "<option>
$name
</option>";
}
} else {
echo "0 results";
}
?>
</select>
</td>
</tr>
</table>
Yet another option would be to use AJAX to call the PHP from the HTML page and return the results to the right location. For instance, if you wanted to use jQuery you could follow a tutorial to learn the basics and then apply that to your code.

Populate an array in flash with data from php

Hi so I need to populate an array in flash with information from php. My php code is :
<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
die("Database connection failed miserably: " . mysql_error());
}
$db_select = mysql_select_db("profileofperson",$db);
if (!$db_select) {
die("Database selection also failed miserably: " . mysql_error());
}
?>
<html>
<head>
<title>mySQLtestfile</title>
</head>
<body>
 
<?php
//Step4
$result = mysql_query("SELECT * FROM catalogue", $db);
if (!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row[" Name"]." ".$row["age"]." ".$row["Allergies"]." ".$row["height"]." ".$row["weight"]."<br />";
}
?>
</body>
</html>
which at present is displaying information from a database. How do i get flash to populate into an array?
Make your document xml, not html, start the document like this:
<?php
header("Content-type: text/xml");
echo chr(60).chr(63).'xml version="1.0" encoding="utf-8" '.chr(63).chr(62);
This just adds a header tag so the browser/flash recognises the document as XML (similar to !DOCTYPE with HTML) : <?xml version="1.0" encoding="UTF-8"?>
Then, query as you are doing, but echo the results in a valid XML format:
echo "<people>";//Create the parent node
while ($row = mysql_fetch_array($result)) {
echo "<person>";//Open child node, add values:
echo "<name>".$row[" Name"]."</name>";
echo "<age>".$row["age"]."</age>";
echo "<allergies>".$row["Allergies"]."</allergies>";
echo "<height>".$row["height"]."</height>";
echo "<weight>".$row["weight"]."</weight>";
echo "</person>";//Close child node
};
echo "</people>";//Close the parent node
?>
I've just written this out off the top of my head so may not be perfect, but it should be easy enough for you to check that it's generating a valid XML document (just load the page in a browser, get an XML viewer plugin to find out more if it's going wrong) and adjust if not, there are millions of tutorials on generating XML pages from PHP.
Then, use the URLLoader class in your flash application to access it:
var loader:URLLoader = new URLLoader();
//The loader class
var urlRQ:URLRequest = new URLRequest('yoursite/yourpage');
//The URL request
loader.dataFormat = URLLoaderDataFormat.TEXT;
//Use this for xml
urlRQ.method = URLRequestMethod.POST;
//Set method type (normally post)
loader.load(urlRQ);
loader.addEventListener(Event.COMPLETE,loadedData);
Then, have loadedData parse the XML:
function loadedData(e:Event):void {
var people:XML = XML(e.target.data);//Cast this var as XML to access
//people should represent top-level ie <people>;
for each(var person:XML in people.person){//Iterate over member nodes called 'person';
trace(person.age);//XML object node names can be referenced
//directly with dot notation!
trace(person.name);//etc...
}
}
One last thing, the mysql_ functions are deprecated in PHP, I found this out recently, use SQLi or PDO instead in future!
Hope this helps, as I say I've written it off the top of my head and it's better that you experiment with it, but if you do get stuck leave a comment and I'll have a look!

Trying to make an function call to an external file with PhP, MySQL using WAMP

I'm sure there is a simple answer to this, but I have been fumbling with everything for almost a week now and surrender. I am trying to build a shopping cart app and every coding solution I build will work when I include the code on the same page, but when I try to use an external page to run the function it does not seem to return the data. I have tried various monitoring techniques to determine what it is happening.
Here is the code for the main page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cart Connection</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<p>Will this display?</p>
<p><a href='<?php echo "showCart.php?PHPSESSID=" . session_id() ?>'>View Cart</a></p>
<?php
$Database = "L3TtL2B5DdY";
$Table = "tblProds";
if (isset($_SESSION['curCart']))
$Cart = unserialize($_SESSION['curCart']);
else
{
if (class_exists("shoppingCart"))
{
$Cart = new shoppingCart();
$Cart->setDatabase($Database);
echo ("<p>If statement ran successfully</p>");
}
else
exit("<p>The shoppingCart class is not available!");
}
$Cart->setTable($Table);
$Cart->getProductList();
$_SESSION['curCart'] = serialize($Cart);
?>
<p><a href='<?php echo "showCart.php?PHPSESSID=" . session_id() ?>'>View Cart</a></p>
</body>
</html>
Here is the relevant code on the "shoppingCart.php" page:
<?php
class shoppingCart
{
private $dbConn = "";
private $dbName = "";
private $tableName = "";
private $orders = array();
private $orderTable = array();
function _construct()
{
$this->dbConn = #new mysqli("localhost", "root", "");
if (mysqli_connect_errno())
die("<p>Unable to connect to the database server.</p>" . "<p>Error Code " .
mysqli_connect_errno() . ": " . mysqli_connect_error() . "</p>");
}
public function setDatabase($Database)
{
$this->dbName = $Database;
#$this->dbConn->select_db($this->dbName)
Or die("<p>Unable to select the database.</p>" . "<p>Error code " . mysqli_errno($this->dbConn) .
": " . mysqli_error($this->dbConn) . "</p>");
}
public function setTable($Table)
{
$this->tableName = $Table;
}
public function getProductList()
{
$sqlString = "SELECT prodID, prodName, prodPrice FROM $this->tableName";
#$qryResult = $this->dbConn->query($sqlString)
Or die("<p>Unable to perform the query.</p>" . "<p>Error code " . mysqli_errno($this->dbConn) .
": " . mysqli_error($this->dbConn) . "</p>");
echo "<table width='100%' border='1'>";
echo "<tr><th>Product ID</th><th>Product Name</th><th>Product Price</th><th>Select Item</th></tr>";
$row = $qryResult->fetch_row();
do
{
echo "<tr><td>{$row[0]}</td>";
echo "<td>{$row[1]}</td>";
echo "<td>{$row[2]}</td>";
echo "<td><a href='showCart.php?PHPSESSID=" . session_id() . "&operation=addItem&productID=" . $row[0] .
"'>Add</a></td></tr>";
$row = $qryResult->fetch_row();
} while ($row);
echo "</table>";
}
......
?>
When I try to load the main page it will display the two lines and that is all. I debugged all the errors when I first created the code and thought it would work. When I wrote the original version of this page I put the "connection" code on the same page and the table displayed fine, so I don't know what else it could be.
I installed WAMP on my Windows XP box and it seems to work fine. I haven't touched the configuration files for any of the programs and all my other test code seems to work fine. It is just when I try to contact an external file.
Any help would be greatly appreciated as I think my brain is turning to mush.
Thanks
You probably need to include the ShoppingCart.php file in your main page, so it has the definition of the ShoppingCart class. Try putting at the top of your main page:
<?php require('ShoppingCart.php'); ?>
What I think might be happening is that the cart object is getting unserialised from the Session, but there is no class definition, so it becomes an instance of an incomplete class. When you then call a method on it you are getting a fatal error. What probably doesn't help is that you may not be displaying errors, so the script will just end. You could also try putting at the top of the main page:
<?php ini_set('display_errors', true); ?>
This should make PHP errors get shown.
Edit
It might be worth pointing out that you can't store a database connection in the session. You need to connect to the server / select the database etc. on every request. I don't think your script is currently doing that.
Also, you can store objects in the session without worrying about the serialisation yourself, here is a quick example:
<?php
//include class definition before starting session.
require('ShoppingCart.php');
session_start();
if (!isset($session['cart'])) {
$session['cart'] = new ShoppingCart();
}
$cart = $session['cart'];
//do stuff to cart
$cart->doSomething();
//changes are now saved back to the session when the script is terminated, without you having to do anything.
You need to
include_once("ShoppingCart.php");
Read up on the different ways to include files
http://www.w3schools.com/PHP/php_includes.asp

Categories