PHP export mysql data to excel sheet - php

I have a filter that the user selects or inputs information, and when they hit submit, a query is generated with this code:
<?php
function displayrecords(){
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
$data3 = $_POST['data3'];
$sql_json = "";
$where = "";
if($data1 != ""){
$where = " `data1` = '".mysql_real_escape_string($data1)."'";
}
if($data2 != ""){
if ( $where != "" ) $where .= " AND ";
$where = " `data2` = '".mysql_real_escape_string($data2)."'";
}
if($data3 != ""){
if ( $where != "" ) $where .= " AND ";
$where = " `data3` = '".mysql_real_escape_string($data3)."'";
}
if ($where != "") $sql_json = "SELECT * FROM `database`" . " WHERE " . $where . ";";
$QueryResult = #mysql_query($sql_json) or die (mysql_error());
echo "<table>"
echo "<tr><th>Data1</th>" . "<th>Data2</th>" . "<th>Data3</th></tr>\n";
while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE) {
echo "<tr><td>{$Row['data1']}</td>";
echo "<td>{$Row['data2']}</td>";
echo "<td>{$Row['data3']}</td></tr>\n";
};
echo "</table>"\n";
}
}
It then spits the data out with this:
<?php displayrecords(); ?>
There are no issues here. The query builder works. The data is rendered to the screen in the table.
What I need to do now is take the data that has been returned to the screen and export it to an excel sheet using another button in the same form as the other submit button. Here is the button that is in the same form:
<input class="btn btn-success btn-small" type="submit" name="get_report" value="Get Report" />
I don't know if I can use another submit button in the same form. I think on have to use a javascript onclick() function. I'm not sure. I just need to export the returned data to excel.
Can anyone help?

A few things to consider:
Don't use $_POST[] within a function. It limits the function to only dealing with POST. Rather, call the function with your POST data.
Have the data retrieved from the database and returned in its own function, something like getTableData(), so that your HTML and your spreadsheet scripts will be able to query the data independently without redundant code.
Also, it is always recommended to use mysqli_ or PDO over mysql_*, as mysql_ is deprecated.
I will not address the database query or the html table display in this answer, as it seems you are quite capable of handling that aspect of the task on your own.
With all that in mind, my method would be the following:
At the end of the HTML table, place a link to a csv file in a subdirectory like so:
<a href='download/some.csv?<?php echo 'data1='.urlencode($_POST['data1'], ENT_QUOTES).'&data2='.urlencode($_POST['data2'], ENT_QUOTES).'&data3='.urlencode($_POST['data3'], ENT_QUOTES).; ?>'>Download CSV</a>
Then, in your download folder, you'll need a .htaccess file with the following contents:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ getFile.php?file=$0 [QSA,L]
Also in your download folder, you'll place a getFile.php file that may look something like this:
<?php
$fileName = (isset($_GET['file'])) ? $_GET['file'] : false;
$data1 = (isset($_GET['data1'])) ? $_GET['data1'] : false;
$data2 = (isset($_GET['data2'])) ? $_GET['data2'] : false;
$data3 = (isset($_GET['data3'])) ? $_GET['data3'] : false;
if($fileName && $data = getTableData($data1, $data2, $data3)) //This would be calling your new function designed specifically to retrieve your data in a multidimensional array
{
header("HTTP/1.0 200 OK");
header("Content-Type: text/csv");
header('Content-Disposition: attachment; filename="'.$fileName.'"');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
foreach($data as $row)
{
foreach($row as $columnCount=>$field)
{
echo ($columnCount) ? ','.csvField($field) : csvField($field);
}
echo "\r\n";
}
}
else header("HTTP/1.0 404 Not Found");
function csvField($value, $textDelimiter = '"')
{
if (strstr($value, $textDelimiter) || strstr($value, ",")) $value = $textDelimiter.str_replace($textDelimiter, $textDelimiter.$textDelimiter, $value).$textDelimiter;
return $value;
}
?>
the .htaccess file passes the file name to your getFile.php script in a $_GET parameter. Your .csv file must not actually exist, so that .htaccess can redirect the request to getFile.php.
Make sure that in your getTableData() function the variables passed are properly protected against SQL injection.

Related

Rewrite URL works when typed manually, but not automatically

Okay so the title of the question may seem vague so here's a full explanation.
My site allows a user to enter a player Username and have the information of that username displayed. the URL of the index page is
http://mcspy.info/
Once the user submits the username, they are taken to another page where it displays the result. The URL now looks like this
http://mcspy.info/php.php?username=_scrunch (_scrunch being a username).
Now by using a .htaccess file to rewrite the URL, a URL can now look like this
http://mcspy.info/player/_scrunch
The Problem is that the above works fine, but the site doesn't generate the URL with /player/Username. It instead uses the php.php?=username.
How would I go about doing it so that when the user submits a username, the URL will automatically show like /player/_scrunch instead of php.php?=_scrunch
Here's my .htaccess file
RewriteBase /
RewriteEngine On
RewriteRule ^player/(.*)$ php.php?username=$1 [L]
Here's my php.php file (Just the PHP code).
<?php
//error_reporting(E_ALL & ~E_NOTICE);
// Load the username from somewhere
if (
$username = $_GET["username"]
) {
//do nothing
} else {
$username = "notch";
}
//allow the user to change the skin
$skinChange = "<a href='https://minecraft.net/profile/skin/remote?url=http://skins.minecraft.net/MinecraftSkins/$username.png' target='_blank' </a>";
//grabbing the users information
if ($content = file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . urlencode($username))
) {
$userSkin3D = "<img src='https://mcapi.ca/skin/3d/$username' />";
$userSkin2D = "<img src='https://mcapi.ca/skin/2d/$username' />";
} else {
$content = file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . urlencode($username) . '?at=0');
if( $http_response_header['0'] == "HTTP/1.1 204 No Content") {
header ('Location: http://mcspy.info/php.php?username=notch');
}
$json = json_decode($content);
foreach ($json as $currentName) {
$currentName = $currentName;
}
$userSkin3D = "<img src='https://mcapi.ca/skin/3d/$currentName' />";
$userSkin2D = "<img src='https://mcapi.ca/skin/2d/$currentName' />";
}
// Decode it
$json = json_decode($content);
// Check for error
if (!empty($json->error)) {
die('An error happened: ' . $json->errorMessage);
}
// Save the uuid
$uuid = $json->id;
// Get the history (using $json->uuid)
$content = file_get_contents('https://api.mojang.com/user/profiles/' . urlencode($uuid) . '/names');
// Decode it
$json = json_decode($content);
$names = array(); // Create a new array
foreach ($json as $name) {
$input = $name->name;
if (!empty($name->changedToAt)) {
// Convert to YYYY-MM-DD HH:MM:SS format
$time = date('Y-m-d H:i:s', $name->changedToAt);
// $input .= ' (changed at ' . $time . ')';
}
$names[] = $input; // Add each "name" value to our array "names"
}
//url to users 2D head (avatar)
$usersAvatar = "https://mcapi.ca/avatar/2d/$input/55";
//user's Avatar as favivon
$usersFavicon = "<link rel='shortcut icon' href='$usersAvatar' type='image/png' />";
//use $uuid tp grab UUID of the user - ---- - - - use $names to get name history of the user.
?>
Try adding this rule above the RewriteRule that you already have:
RewriteCond %{THE_REQUEST} \ /+php\.php\?username=([^&\ ]+)
RewriteRule ^ /player/%1? [L,R]
in order to redirect direct requests to the php.php file to the cleaner looking URL. Then your other rule will internally rewrite it back to the php.php one.

PHP echo printing language construct

In an assignment I'm having trouble running a php script with page handling. It's outputting actual php code when submitted through another php page but works fine on its own.
I have a html login page which submits via submit buttons rather than form submit [a requirement]. This submits to login.php.
Seperately I have testBalance.php which checks a file balance.txt on my server which simply has an amount (1000). testBalance.php calls a function in getBalance.php to return the amount here.
THE PROBLEM IS when I run testBalance.php by itself it works just fine. Displaying "Account Balance: 1000.00" but when I attempt to set (in login.php) testBalance.php as the redirect url, the page literally displays code from my testBalance.php page: "Account balance: "); printf ( "%01.2f", $returnValue ); echo ("
"); ?> " I know it's convoluted, this is an intro to php portion of an web prog. class. I'm guessing it has to do with the value pairs that are being passed through to the pages. Can anyone help?
LOGIN.HTML snippit
<input type="button" name="sub_but" id="bal" value="check balance"
onclick="location.href = 'login.php' + '?' + 'name='+ document.forms[0].username.value +
'&redirectURL=' + 'bal';" />
LOGIN.PHP
<?php
$NAME=$_GET["name"];
$PAGE=$_GET["redirectURL"];
$DESTINATION="";
if ($NAME == ''){ /* HANDLES NAME ERRORS */
echo "PLEASE RETURN AND ENTER A NAME.";
}
elseif (ctype_alpha(str_replace(' ', '', $NAME)) === false) {
echo "$NAME is not a valid name. Name must contain letters and spaces only";
}
else{
if($PAGE=='with'){
$DESTINATION = "withdraw.html";
}
elseif($PAGE=='bal'){
//$DESTINATION = "balance.html";
$DESTINATION = "testBalance.php";
}
elseif($PAGE=='depos'){
$DESTINATION = "deposit.html";
}
elseif($PAGE=='weath'){
$DESTINATION = "weather.html";
}
elseif($PAGE=='xchang'){
$DESTINATION = "currency.html";
}
/*echo("$DESTINATION\r\n");*/
header("Content-Length: " .
strlen(file_get_contents($DESTINATION)));
header("Cache-Control: no-cache");
readfile($DESTINATION);
}
?>
testBalance.php body snippit
<?php
include 'getBalance.php';
$returnValue = readBalance();
echo "<p>Account balance: ";
printf( "%01.2f", $returnValue );
echo "</p>";
?>
getBalance.php
<?php
function readBalance(){
$file = "balance.txt";
$fp = fopen($file, "r");
if (!$fp){
echo "<p>Could not open the data file.</p>";
$balance = 0;
}
else{
$balance = fgets($fp);
fclose ($fp);
}
return $balance;
}
?>
readfile() doesn't EXECUTE anything it reads. It's literally just slurping in the file's bytes and spitting them out to the client. It's basically doing
echo file_get_contents(...);
If you want your other files to be executed, you need to include() or require() them instead. Or you could try eval(), but you really don't want to go down that route. eval() is evil and dangerous.

PHP - download dialog box for given videos url

I am pretty new in php .so hopefully this all make sense . I am using below script to extract url from database.I want down-loader will popup in browser while reading the url from database....
$q=" Select url from videos where id = '".$_REQUEST['id']."' ";
$result=mysql_query($q);
while( $rows =mysql_fetch_assoc($result) )
{
$url=$rows['url '];
//here i want code to send this url to down-loader of browser..
//and browser should popup the down-loader
$myarray1=array("url "=>$url );
}
I have searched codes on google but i don't understand how to use for this scenario...
First of all, you need to fix the SQL Injection problem.
Use MySQLi instead of MySQL
Here's a code:
$request_id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
if(!empty($request_id)){
$mysqli = new mysqli("localhost", "user", "password", "database_name");
$request_id = $mysqli->real_escape_string($request_id);
$query = "SELECT url FROM videos WHERE id='" . $request_id . "'";
$query_result = $mysqli->query($query);
if(!empty($query_result)){
if($query_result->num_rows > 0){
$my_result_array = array();
while($row = $query_result->fetch_assoc()){
$my_result_array[] = $row['url'];
}
}
}
mysqli_close($mysqli);
}
Concerning the download problem, you need to redirect the user to a PHP page with a specific header
<?php
$file_name = "";
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"" . $file_name . "\"");
header("Cache-Control: max-age=0");
?>
You need to add the $file_name and the specific Content-Type.
Here's a list of Content-Types: http://davidwalsh.name/php-header-mime
In order to redirect a user to the download page, you can use the PHP header() function.

download button - save file to disk instead of opening

I have a download button and when i click on it, instead of saving to disk it opens it in the browser. I tried a bunch of attempts to make it open in the browser but it doesnt seem to do anything
<?php
// make a connection to the database
require_once("connection/connection.php");
//retrieve the ID from the url to fetch the specific details
if ($_GET['id'] != ""){
$item_id = $_GET['id'];
$bad_id = FALSE;
}
else{
$item_id = "";
$bad_id = TRUE;
}
//select the specific item from the database
// run if statement to ensure valid id was passed
if (is_numeric ($_GET['id'])){
$query = "SELECT name FROM repository WHERE item_id = '$item_id'";
$result = mysql_query($query) or die(mysql_error());
// assign the values to an array
$row = mysql_fetch_assoc($result);
//assign the values from the array to variables
$name = $row['name'];
}
// define path to the xml file
$file = "xml/".$hud_name . "_cfg.xml";
// check to make sure the file exists
if(!file_exists($file)){
die('Error: File not found.');
} else{
// Set headers
header("Content-Type: application/xml");
header("Content-Disposition:attachment; filename=".basename($file)."");
readfile($file);
}
?>
That is download.php and it obviously finds the file because it doesnt give the error about it not existing. It also echos back the correct file path
Then on another page i have:
<img src="images/download.png" alt=""/>
Any ideas whats wrong?
Well the solution turned out to be simple in the end but i didnt see any documentation saying the header must be the very first line. If i placed:
header("Content-Type: application/xml");
as the first line and then the coding below it and the other header info at the end it works. Im not sure if that's the solution or a workaround but it fixed it for me

HTML Form Not Outputting To CSV File (Or Displaying Correct Error Messages)

I'm having trouble creating a form that exports to a .CSV file in PHP. I created a fiddle for the HTML which is here:
http://jsfiddle.net/tqs6g/
I'm coding in PHP so I can't really show the full code on JSFiddle since it can't support the PHP but here's my PHP code:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['brandname']))
{
$errorMessage .= "<li>Please enter a business/brand name.</li>";
}
if(empty($_POST['firstname']))
{
$errorMessage .= "<li>Please enter your first name.</li>";
}
$varBrand = $_POST['brandname'];
$varFName = $_POST['firstname'];
$varLName = $_POST['lastname'];
$varEmail = $_POST['email'];
$varSite = $_POST['website'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varBrand . ", " . $varFName . ", " . $varLName . ", " . $varEmail . ", " . $varSite . "\n");
fclose($fs);
exit;
}
}
?>
When I click Submit it successfully goes to 'thankyou.php' (which is set in the form action) but I can't figure out why it's not posting the correct error messages or filling in my 'mydata.csv' file upon click. Possibly it's a sight syntax error? Let me know if you need any more info, I know this is kind of confusing seeing as the PHP is separated from the Fiddle.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // better method to check for a POSt
... validation stuff ...
$data = array();
$data[] = $_POST['brandname'];
$data[] = $_POST['firstname'];
etc...
if (empty($errrorMessage)) {
$fs = fopen('mydata.csv', 'a') or die("Unable to open file for output");
fputcsv($fs, $data) or die("Unable to write to file");
fclose($fs);
exit();
} else {
echo $errormessage;
}
}
A few things of note:
1) using $_SERVER['REQUEST_METHOD'] to check for submit type is absolutely reliable - that value is always set, and will always be POST if a post is being performed. Checking for a particular form field (e.g. the submit button) is hacky and unreliable.
2) Using fputcsv() to write out to a csv file. PHP will do all the heavy work for you and you jus tprovide the function an array of data to write
3) Note the or die(...) constructs, which check for failures to open/write to the file. Assuming that a file is available/writeable is unreliable and will bite you at some point in the future. When dealing with "external" resources, always have error handling.

Categories