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.
Related
I have this PHP code that fetches data (an image link and some strings) from my database. The goal is for me to be able to add products (its for an online store) to the database and have that PHP file automatically fetch the data required to display it on the site. I've managed to pull the data I needed but I can't seem to find a way to add some CSS to the divs it creates for each product.
I have already tried linking a CSS file and I don't want to go adding it inline (defeats the purpose of it being automatic)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>testdoc</title>
<style>
.prodimg
{
border: 20px, red, solid;
}
</style>
</head>
<body>
</body>
</html>
<?php
include 'db_connection.php';
$conn = OpenCon();
echo "Connected Successfully";
//query voor var
$sql = "SELECT prod_id, prod_name, stock, prod_price,images FROM PRODUCTS WHERE prod_name = 'red shirt' OR prod_type = 'tshirt'";
$result = $conn->query($sql); // kijken of er results zijn
$numberofRows=0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
makeDiv($numberofRows,$row);
}
}
else {
echo "0 results";
}
$conn->close();
function makeDiv($numberofRows,$row)
{
$doc = new DOMDocument;
$div = $doc->createElement('div');//Create new <div> tag
$div->setAttribute('class',"prodimg"); // give it a class
$imglink = $doc->createElement('img'); //create new image
$doc->appendChild($div);//Add the <div> tag to document
$imglink->setAttribute('src',$row['images']); //add the source from the database
$imglink->setAttribute('width',"200px");//give it the right size
$imglink->setAttribute('margin',"50px"); // setattribute seems to only work once for some reason
$div->appendChild($imglink); //add the image to the div
echo $doc->saveHTML(); // save everything
}
?>
You could add style block to the page
<style>.prodimg { background: #FF6600 }</style>
Screenshot of issue
I am creating a messaging application and want to make emoji images viewable rather than showing their codes in the messages.
I have used an emoji picker js file for entering them in the text area but in sent messages the emoji icon is not showing.
I use the following function :
function loadMessages($token){
// this function is loads all the messages from the database
$db = connect();
$me = $_SESSION['id'];
$query = $db->prepare("SELECT * FROM messages WHERE (fromm=:fromm1 AND too=:too1) OR (fromm=:too2 AND too=:fromm2) ");
$query->bindParam(':fromm1',$me);
$query->bindParam(':too1',$token);
$query->bindParam(':too2',$token);
$query->bindParam(':fromm2',$me);
$query->execute();
$found = $query->rowCount();
if($found){
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$from = $row['fromm'];
$to = $row['fromm'];
$message = $row['message'];
$text = $row['message'];
$html = preg_replace("/\\\\u([0-9A-F]{2,5})/i", "&#x$1;", $message);
if($from == $me){
$realMessage = "<div class='me'> $html <br /><br /></div>";
} else {
$realMessage = "<div><div class='you'>$html<br /><br /></div></div>";
}
echo $realMessage;
}
The main index.php includes this:
<div class="display-message" style="position: absolute; width: 100%; padding: 10px; background: inherit; bottom: 0;">
</div>
Hi and welcome to Stack Overflow.
There is an encoding issue. You are seeing the Latin output of the characters rather than Unicode (is your database encoding set to something other than UTF-8?).
Get PHP to output the following header before any other output:
header('Content-type: text/html; charset=utf-8');
Add the following meta tag in your <head> section:
<meta charset="utf-8">
And in your loop:
...
while($row=$query->fetch(PDO::FETCH_ASSOC)){
$from=$row['fromm'];
$to=$row['fromm'];
$message=preg_replace("/\\\u([0-9A-F]{2,5})/i","&#x$1;",$row['message']);
$message=mb_convert_encoding($message,'UTF-16','HTML-ENTITIES');
$html=mb_convert_encoding($message,'UTF-8','UTF-16');
...
found a couple answers here on StackOverflow and used them as my models, but I must be missing something. I'm trying to set a couple of background colors dynamically in CSS based on what is in my database, but it's not working - when I check Inspect Element in Chrome, background-color has a line through it and a warning mark for 'Invalid property value'.
Here's my code; it's in two separate files - the first is in the header include file, and the second is in the linked .php / css-esque file.
Header include: [Edited 4/29 to include session code]
session_start();
// check if $_SESSION was set before
if (!isset($_SESSION['email'])) {
header("Location: bad_login.php");
exit();
}
$_SESSION['companyid'] = $_POST['companyid'];
$companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];
require_once('../includes/_connection.inc.php');
$connect = dbConnect('read');
$sql = 'SELECT colorone, colortwo, logo
FROM companies
WHERE companyid = ' . $companyID;
$result = $connect->query($sql) or die(mysqli_error());
$row = $result->fetch_assoc();
$colorOne = '#' . $row['colorone'];
$colorTwo = '#' . $row['colortwo'];
$carrierLogo = '/companylogos/' . $row['logo'];
PHP/CSS file:
<?php header("Content-type: text/css");
?>
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: <?php echo $colorOne; ?>;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: <?php echo $colorTwo; ?>;
}
EDIT 4/29:
This is the CSS generated:
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: ;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: ;
}
I also echoed the variable back in the html so I know that there should be something in the variable. Should I be opening the database and assigning the variable inside the css.php file?
CSS/PHP is linked this way in header:
<link type="text/css" rel="stylesheet" href="../css/carrier.php">
Instead of using the .css file extension, use .php
in the html file: is it linked to .php?
<link rel='stylesheet' type='text/css' href='css/style.php' />
in the style.php add
<?php
header("Content-type: text/css; charset: UTF-8");
?>
Now you can set up variables for whatever you like:
source
Edit:
Don't forget about session_start(); since you're using sessions (I don't understand how, since nothing gets posted to css/carrier.php you should rather have it in session from a different file & then just use the $companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];).
is this the way your code looks?
<?php
session_start();
header("Content-type: text/css; charset: UTF-8");
$_SESSION['companyid'] = $_POST['companyid'];
$companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];
require_once('../includes/_connection.inc.php');
$connect = dbConnect('read');
$sql = 'SELECT colorone, colortwo, logo
FROM companies
WHERE companyid = ' . $companyID;
$result = $connect->query($sql) or die(mysqli_error());
$row = $result->fetch_assoc();
$colorOne = '#' . $row['colorone'];
$colorTwo = '#' . $row['colortwo'];
$carrierLogo = '/companylogos/' . $row['logo'];
?>
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: <?php echo $colorOne; ?>;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: <?php echo $colorTwo; ?>;
}
The answer of yesitsme is correct. Other thing you can do is that each storage changes in the database, run the process of creating this "new" CSS file with the appropriate .css extension.
What if with every request you create a new CSS file?
I mean, you have two paths, when creating the first call to the Web and update it from time to time, either, at the time you keep the data in the database associating it to a script.
With this new CSS and stored is generated through fwrite () and other functions that PHP has to manage files, keep the name of the CSS created in the BDD and then in your place the link as appropriate.
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.
I am trying to use html2pdf to create pdf of the php file which contains a table in vich th data from mysql database is fetched and is generated by using while loop, but wen I try to run the php file it says the follwoing error
TCPDF ERROR: Some data has already been output, can't send PDF file
can anyone help me in solving the problem please? here is my code:
<?php
session_start();
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
//error_reporting(0);
/*
Author : yaser kazi
Description : This File Contain Additions and Editing part for the Paxes
*/
if (!isset($_SESSION["username"])) {
header("location: unauthorize_access.html");
exit();
}
if (isset($_GET["cityprin"])) {
mysql_connect("localhost", "root", '') or die(mysql_error());
mysql_select_db('webapp') or die(mysql_error());
$get = mysql_query("SELECT code, `name` FROM city ORDER BY `name`") or die(mysql_error());
$ctr = 0;
ini_set("memory_limit", "50M");
ob_start();
?>
<style type="text/css" media="all">
<!--
body {
margin:0px;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
}
span {
font-size:14px;
}
td {
width: 100mm;
max-width: 100mm;
height: 33mm;
max-height:33mm;
top:0mm;
}
table {
border-collapse:collapse;
}
-->
</style>
<?php
echo "<table border=\"1\" align=\"right\" style =\"width: 205mm;\">";
echo "<th>Srno</th>";
echo "<th>Code</th>";
echo "<th>Name</th>";
while ($city = mysql_fetch_array($get)) {
$ctr++;
echo "<td style=\"width: 100mm; max-width: 100mm; height:33mm; padding-left:1mm;\" valign=\"right\">".$ctr."</td>";
echo "<td style=\"width: 100mm; max-width: 100mm; height:33mm; padding-left:7mm;\" valign=\"right\">".$city['code']."</td>";
echo "<td style=\"width: 100mm; max-width: 100mm; height:33mm; padding-left:7mm;\" valign=\"right\">".$city['name']."</td>";
}
echo "</table>";
} // Submit Tag Close
?>
<?php
$content = ob_get_clean();
// conversion HTML => PDF
require_once('html2pdf/html2pdf.class.php');
try {
$html2pdf = new HTML2PDF('P', 'A4', 'EN', false, 'ISO-8859-15', array("5mm", "13mm", "0mm", "0mm"));
$html2pdf->pdf->SetAuthor('CepheiSys');
$html2pdf->pdf->SetTitle('City_list');
// $html2pdf->pdf->SetSubject('HTML2PDF Wiki');
// $html2pdf->pdf->SetKeywords('HTML2PDF, TCPDF, example, wiki');
$html2pdf->setDefaultFont('Arial');
$html2pdf->writeHTML($content);
$html2pdf->Output('City_list.pdf');
} catch (HTML2PDF_exception $e) {
echo $e;
}
?>
You've got some sort of output before you're outputting those headers it seems. There are a few things to check:
Do you have any echo statement (or similar) earlier in the code?
Is there any sort of space before that PHP tag? A new line or tab would trigger output being sent to the browser
Have you turned off the BOM feature in your editor, as this can cause problems with UTF8 documents and trigger output to be sent to the browser
Check the error logs, there should be a line number to go with that error. It should give you an idea of where to start looking