sqlsrv to csv using PHP - php

I have been work on a PHP page that will export some SQL data using sqlsrv_fetch_array to a csv file. I am having some problems with getting the data just right in the csv file. When I run the script the output on the csv file looks like this.
<html>
<head>
<title>Page Title</title>
</head>
<body>
" "
" "
"CCCCCCC\SSSSS" 140211 B Insxxxxxx BBB Y N CCCCCCC\SSSSS Stevens_Dave Y
CCCCCCC\SSSSS 140211 W Insxxxxxx BBB Y N CCCCCCC\SSSSS Stevens_Dave Y
CCCCCCC\SSSSS 140411 R Intxxxxx Auxxx BBB Y N CCCCCCC\SSSSS Stevens_Dave Y
Notice that the first "CCCCCC\SSSS" still has the " around it even though the rest of the information does not. Also for some reason it is posting the HTML stuff at the top of the csv file. I would like it to put the headers there but can't seem to figure out how to get it working. Can you take a look at the code and let me know where the problem is along with how to add the headers to the csv file as well? Here is the code.
<html>
<head>
<title>Page Title</title>
</head>
<body>
<?php
$userid = $_POST['userid']; //defined through a form
$serverName = "server1, 1433";
$connectionInfo = array("UID"=>"adminweb", "PWD"=>"adminweb", "Database"=>"dbname");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Set up and execute the query. */
$sql = "SELECT * FROM UserProfile u INNER JOIN UserTeam ut ON u.UserID = ut.UserOrTeam WHERE UserID LIKE '%xxxx%'";
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
foreach($row AS $key => $value){
//If the character " exists, then escape it, otherwise the csv file will be invalid.
$pos = strpos($value, '"');
if ($pos !== false) {
$value = str_replace('"', '\"', $value);
}
$out .= '"'.$value.'",';
}
$out .= "\n";
}
sqlsrv_free_stmt($results);
sqlsrv_close($conn);
// Output to browser with the CSV mime type
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=testcsv.csv");
echo $out;
?>
</body>
</html>

Try removing...
<html>
<head>
<title>Page Title</title>
</head>
<body>
from the top of your PHP script.

Related

HTML using a PHP script

im new in php programming and ive a problem recently. I have 1 html page with a Search Box and a php script using for grep in a specific file on local host. This is what i want, when a user type string of char and click on enter that send a POST to modify my php var $contents_list, and grep all filename where the string is found.
<?php
$contents_list = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir = new RecursiveDirectoryIterator($path);
$compteur = 0;
foreach(new RecursiveIteratorIterator($dir) as $filename => $file) {
$fd = fopen($file,'r');
if($fd) {
while(!feof($fd)) {
$line = fgets($fd);
foreach($contents_list as $content) {
if(strpos($line, $content) != false) {
$compteur+=1;
echo "\n".$compteur. " : " . $filename. " : \n"."\n=========================================================================\n";
}
}
}
}
fclose($fd);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="page2.php" method="post">
<INPUT TYPE = "TEXT" VALUE ="search" name="search">
</form>
</body>
And when i go to my html page and type text in searchbar, that redirect me to my php script "localhost/test.php" and i have 500 internal error.
So I want:
To see result of the php script on the same html page, but i dont know how to do that :/
And if the previous filename return was same like previous result, dont print it, to avoid double result.
I hope its clear and youve understand what i want to do, so thanks for the people who want to help me <3
My recommendations:
Combine the code into the single index.php file for simplicity
Separate logic for search and output to achieve clean separation of duties
Add helper text such as nothing found or enter text
index.php content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<form action="index.php" method="post">
<input type="text" placeholder="search" name="search">
</form>
<?php
// Check if the form was submitted.
if (isset($_POST['search']) && (strlen($_POST['search'])) > 0) {
$search_line = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir_content = new RecursiveDirectoryIterator($path);
// Array to store results.
$results = [];
// Iterate through directories and files.
foreach (new RecursiveIteratorIterator($dir_content) as $filename => $file) {
$fd = fopen($file, 'r');
if ($fd) {
while (!feof($fd)) {
$file_line = fgets($fd);
if (strpos($file_line, $search_line) !== FALSE) {
$results[] = $filename;
}
}
fclose($fd);
}
}
// Output result.
echo "<pre>";
if ($results) {
foreach ($results as $index => $result) {
echo ($index + 1) . " :: $result\n";
}
}
else {
echo "Nothing found!";
}
echo "</pre>";
}
else {
// When nothing to search.
echo "<pre>Enter something to search.</pre>";
}
?>
</body>
</html>

Value NULL after program compile in browser

I'm making an application to remove additive or commonly called Stemming confix stripping. I wanted to make a loop to process stemming in each text file. process stemming I've put them in the loop. making the process the content of each document also I put in a text file. when I run in the browser no error but only the note NULL. what's the solution? I attach my program and program results`it is code
<?php
require_once __DIR__ . '/vendor/autoload.php';
$array_sentence = glob('../../ujicoba/simpantoken/*.txt');
settype($array_sentence, "string");
if(is_array($array_sentence) && is_object($array_sentence))
{
foreach ($array_sentence as $text)
{
$textnormalizer = new src\Sastrawi\Stemmer\Filter\TextNormalizer();
$stemmerFactory = new \Sastrawi\Stemmer\StemmerFactory();
$stemmer = $stemmerFactory->createStemmer();
$content = file_get_contents($text);
$stemmer = $stemmerFactory->createStemmer();
$output = $stemmer->stem(array($content));
echo $output . "\n";
}
}
var_dump($content);
?>
<!DOCTYPE html>
<html>
<head>
<title>Confix Stripping Stemmer</title>
</head>
<body>
</body>
</html>
my source code result in browser when running programenter code here
On l.4, settype($array_sentence, "string"); force $array_sentence as a string, which means is_array($array_sentence) && is_object($array_sentence) will return false.
The following code works for stemming:
<?php
include('stopword.php');
$regexRules = array(
'/^be(.*)lah$/',
'/^be(.*)an$/',
'/^me(.*)i$/',
'/^di(.*)i$/',
'/^pe(.*)i$/',
'/^ter(.*)i$/',
'/^di(.*)kan$/',
'/^di(.*)nya$/',
'/^di(.*)kannya$/',
'/^mem(.*)pe$/',
'/^meng(.*)g$/',
'/^meng(.*)h$/',
'/^meng(.*)q$/',
'/^meng(.*)k$/',
'/^mem(.*)kan$/',
'/^diper(.*)i$/',
'/^di(.*)i$/',
'/^memper(.*)kan$/',
'/^meny(.*)i$/',
'/^meny(.*)kan$/',
'/^men(.*)kan$/',
'/^me(.*)kan$/',
'/^meng(.*)nya$/',
'/^memper(.*)i$/',
'/^men(.*)i$/',
'/^meng(.*)i$/',
'/^ber(.*)nya$/',
'/^ber(.*)an$/',
'/^ke(.*)an$/',
'/^ke(.*)annya$/',
'/^peng(.*)an$/',
'/^peny(.*)an$/',
'/^per(.*)an$/',
'/^pen(.*)an$/',
'/^pe(.*)an$/',
'/^ber(.*)$/',
'/^di(.*)$/',
'/^men(.*)$/',
'/^meng(.*)$/',
'/^meny(.*)$/',
'/^mem(.*)$/',
'/^pen(.*)$/',
'/^peng(.*)$/',
'/^ter(.*)$/',
'/^mem(.*)$/',
'/^(.*)nya$/',
'/^(.*)lah$/',
'/^(.*)pun$/',
'/^(.*)kah$/',
'/^(.*)mu$/',
'/^(.*)an$/',
'/^(.*)kan$/',
'/^(.*)i$/',
'/^(.*)ku$/',
);
global $regexRules;
$file_string = glob('yourfoldertoseavedata_text/*.txt');
$string = array('(.*)');
foreach ($file_string as $data)
{
$string[] = file_get_contents($data);
$stemming = str_ireplace($regexRules,"", $string);
var_dump($stemming);
}
?>

creating a textbox from a non-txt fopen file

I have the following code that opens a non-txt file and runs through it so it can read the file line by line, i want to create a textbox (using html probably) so i can put my readed text into that but i have no idea how to do it
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h2>testing</h2>
<?php
$currentFile = "pathtest.RET";
$fp = fopen($currentFile , 'r');
if (!$fp)
{
echo '<p> FILE NOT FOUND </p>';
exit;
}
else
{
echo '<p><strong> Arquivo:</strong> ['. $currentFile. '] </p>';
}
$numLinha = 0;
while (!feof($fp))
{
$linha = fgets($fp,300);
$numLinha = $numLinha + 1;
echo $linha;
}
fclose($fp);
$numLinha = $numLinha -1;
echo '<hr>linhas processadas: ' . $numLinha;
?>
</body>
</html>
i need the textbox area to be in a form so i can define the cols and rows, or there is an way to do it in php ? is there any way to send the readed content to another .php so i can edit the php to an html interface style freely ?
Try echoing the lines between a textarea:
echo "<textarea>";
while (!feof($fp))
{
$linha = fgets($fp,300);
$numLinha = $numLinha + 1;
echo $linha;
};
echo "</textarea>";
You may use \n in order to break lines on the textarea:
echo $linha . "\n";

PHP Creating a file to send, output buffer already sent?

Hey I guys I wrote a function to force out a json file, but it seems that the buffer concatenating the file somehow. Normally it should just be a JSON object, but it looks
like the page itself is being inserted into the file?
[{"key":"16","role":null,"region":"Great White North","inspection_type":"citrus","inspection_number":"996","customer_number":"206-420-9564","report_date":"2012-10-21","status":"1","order_date":"2012-02-23 15:24:34","customer":"Jd Daniel","customer_division":"Field worker","memo":null,"billing_key":null,"report_key":"996","shipper":"Hanjin","po":"33215","location":"Boulder, CO","inspector":"Newman","commodity":"Apples","count":"32","size":"medium","label":"Granny Smith","variety":"Golden","pack_date":"0000-00-00","grower_lot":"Lots to grow","color1":"4","color2":"15","texture1":"","texture2":"","puff1":"","puff2":"","scar1":"","scar2":"","solidity1":"","solidity2":"","green1":"","green2":"","sugar_brix1":"","sugar_brix2":"","rating":"0","comments":"Comments 1"},{"key":"17","role":null,"region":"Great White North","inspection_type":"citrus","inspection_number":"996","customer_number":"206-420-9564","report_date":"2012-10-21","status":"0","order_date":"2012-02-23 15:24:34","customer":"Jd Daniel","customer_division":"Field worker","memo":null,"billing_key":null,"report_key":"996","shipper":"Jiun Ming","po":"4215","location":"South Holywood","inspector":"Gadget","commodity":"Grapes","count":"29","size":"46","label":"sweet","variety":"green","pack_date":"0000-00-00","grower_lot":"","color1":"","color2":"","texture1":"","texture2":"","puff1":"","puff2":"","scar1":"","scar2":"","solidity1":"","solidity2":"","green1":"","green2":"","sugar_brix1":"","sugar_brix2":"","rating":"0","comments":"Comments 2"}]
<!DOCTYPE html>
<html lang="en-US">
<head>
<title> </title>
<script src='http://www.google.com/jsapi'></script>
<script> google.load('jquery', '1.7.1'); </script>
<style type="text/css">
body {font-family: arial;}
p, ul {width:100%; text-align:left;font-size:80%;}
.reports_box {width:auto; padding:25px 20px 20px 20px;border:1px solid #91bce6;background-color:#eff5fb;}
input {width:121px; font-size:15px;padding:5px;}
.check input {padding:0 !important;}
.caps {text-transform:capitalize;}
Weird right? I can't get the buffers to flush right to remove this and am hoping for a better way to get this working. Here's my function.
function getReportDown($array) {
unset($array['select']);
$cleanArray = filter_var_array($array ,FILTER_SANITIZE_STRING);
$array=array(); // needs to be secured -jd
foreach($cleanArray as $k=>$v) {
if(strpos($k,'find_') === false) {
$array[] = explode(':',$k); }
}
require('perms.php.inc');
require('dbconnect.class.inc');
$dbc = Database::obtain(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$dbc->connect();
$form=array();
foreach($array as $key=>$val) {
$form[] = array_pop($dbc->fetch_array("SELECT * FROM reports JOIN ( SELECT * FROM `{$val[0]}` WHERE `key` = {$val[1]}) fruits ON inspection_number = fruits.report_key ORDER BY report_date DESC"));
}
$dbc->close();
$rand = randomAlphaNum(10).'.json';
header("Content-type: application/json");
header("Content-disposition: attachment; filename=$rand");
header('Content-Transfer-Encoding: binary');
echo json_encode($form);
//unlink($rand);
}
exit or die after you echo the JSON.

Use php for Output Buffering and jQuery to send ob_get_contents

I am trying to capture the contents of my php page using output buffering:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$sectionOne[] = $row;
}
}else{
//error - sql failed
}
}
?>
<?php
ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#export").click(function(e){
//post to html2pdfconverter.php
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
$("#nm").val("Entry Report.pdf");
$("form#sendanswers").submit();
});
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
<form id = "sendanswers" name = "sendanswers" action="html2pdfconverter.php" method="post">
<input type = "hidden" name = "link" id = "link" value = "">
<input type = "hidden" name = "nm" id = "nm" value = "">
<input type = "button" name = "export" id = "export" value = "Export As PDF"/>
</form>
</div>
<h3>Biological Information</h3>
<?php
echo('<p>');
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
echo('</p>');
?>
</body>
</html>
<?php
}
$contents = ob_get_contents(); //THIS WORKS
ob_end();
?>
I assign the contents of ob to $contents using ob_get_contents(); This works, and echoing $contents duplicates the html page.
However, in my jQuery, I am trying to assign this to a hidden text field ('link') using:
$("#link").val("<?php echo($contents); ?>");
This doesn't work however..And I have a feeling its because I am accessing $contents too eraly but not too sure...any ideas?
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
at the point you do that ob_get_contents call, you've only output about 10 lines of javascript and html. PHP will NOT reach back in time and magically fill in the rest of the document where you do this ob_get_contents().
You're basically ripping the page out of the laser printer the moment the page starts emerging, while the printer is still printing the bottom half of the page.
I fail to see why you want to embed the contents of your page into an input field. If you want to somehow cache the page's content in an input field, you can just use JS to grab the .innerHTML of $('body').
Well, you have two problems.
The first is what you suspect. You can't access that stuff until later. The second problem which you may not realize is that you will have quoting issues in JavaScript even if you manage to find a way to reorder this and make it work. It's recursive, in a bad way.
What you should do instead is change your $('#export').click handler to do an Ajax call, render the HTML you need to appear in the link on the server in a separate PHP script (no output buffering necessary) and then have your code inject the result of that call into the page the way you're trying to do in your click handler now.

Categories