My goal here is to have the browser download a csv file using headers to do it. For some reason yet to be determined, the browser seems to be downloading the HTML content of the current page (and not the contents of the array I've given it).
Here is the code I've been using:
$arr1 = array(array("1","2","3","4"),array("2","1","6","6"));
$tmp_handle = fopen('php://memory', 'r+');
fputcsv($tmp_handle, $arr1);
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
rewind($tmp_handle);
echo stream_get_contents($tmp_handle);
I've followed the instructions of many articles / SO questions I've read and I don't see what's wrong with this code.
I of course appreciate any help that I can get here!
Here is the complete code (upon request):
<?php
global $wpdb;
// Get total number of active referrers
$referrer_check = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."referrer");
$num_of_referrers = 0;
foreach ( $referrer_check as $check)
{
$num_of_referrers++;
}
// Get total number of referral transactions
$num_of_referrals = 0;
$num_referral_check = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."referrer_transactions");
foreach ( $num_referral_check as $check)
{
$num_of_referrals++;
}
// Check for the top referrer
$top_referrer = $wpdb->get_row("SELECT referrer_id, count(*) as row_count FROM ".$wpdb->prefix."referrer_transactions GROUP BY referrer_id ORDER BY COUNT(*) DESC");
$top_referrer_result = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."referrer WHERE referrer_id = $top_referrer->referrer_id");
// Construct the table
// Create array for second table
$ref_transactions_table_arr = array(
array("Referee Name", "Referee ID", "Referee Sign Up", "Referee Email","Referrer ID","Referrer Name"));
foreach ($num_referral_check as $check)
{
$ref_transactions_table_arr[] = array(
$wpdb->get_var("SELECT billing_name FROM ".$wpdb->prefix."pmpro_membership_orders WHERE user_id = $check->buyer_id"),
$check->buyer_id,
$wpdb->get_var("SELECT user_registered FROM ".$wpdb->prefix."users WHERE ID = $check->buyer_id"),
$wpdb->get_var("SELECT user_email FROM ".$wpdb->prefix."users WHERE ID = $check->buyer_id"),
$wpdb->get_var("SELECT referrer_id FROM ".$wpdb->prefix."referrer WHERE referrer_id = $check->referrer_id"),
$wpdb->get_var("SELECT referrer_name FROM ".$wpdb->prefix."referrer WHERE referrer_id = $check->referrer_id")
);
}
// Create array for first table
$active_ref_table_arr = array(
array('Referrer Name', 'Referrer ID', '# of Referrals', 'Address','Referrer Email','Lifetime Referrals'));
foreach ( $referrer_check as $check)
{
$active_ref_table_arr[] = array(
$check->referrer_name,
$check->referrer_id,
$wpdb->get_var("SELECT count(*) FROM ".$wpdb->prefix."referrer_transactions WHERE referrer_id = $check->referrer_id"),
$check->referrer_street . " " . $check->referrer_city . ", " . $check->referrer_state . " " . $check->referrer_zip,
$wpdb->get_var("SELECT user_email FROM ".$wpdb->prefix."users WHERE ID= $check->referrer_id"),
$wpdb->get_var("SELECT count(*) FROM ".$wpdb->prefix."referrer_transactions WHERE referrer_id = $check->referrer_id")
);
}
// Download file
if(isset($_POST['export_tbl_one']))
{
$csvData = array(
array("1","2","3","4"),
array("2","1","6","6")
);
$fp = fopen('php://memory', 'w+');
/*foreach ($csvData as $row) {
fputcsv($fp, $row);
}*/
fputcsv($fp,$csvData);
rewind($fp);
$csvFile = stream_get_contents($fp);
fclose($fp);
header('Content-Type: text/csv');
header('Content-Length: '.strlen($csvFile));
header('Content-Disposition: attachment; filename="file.csv"');
exit($csvFile);
}
?>
<div class="nav">
<ul>
<li class="first">Total Referrers: <? echo $num_of_referrers; ?></li>
<li>Total Referals: <? echo $num_of_referrals; ?></li>
<li>Top Referrer: <? echo $top_referrer->referrer_id . ", " . $top_referrer_result->referrer_name . "(" . $top_referrer->row_count . ")"; ?></li>
<li>
<form method="POST" action="http://keepmecertified.com/acp">
<input type="submit" value="click me" name="export_tbl_one"/>
</form>
</li>
</ul>
</div>
<br>
<table class="table">
<caption>Referrer Transactions</caption>
<?
$num = 0;
foreach($ref_transactions_table_arr as $fields)
{
echo "<tr>";
foreach($fields as $data)
{
if($num == 0)
{
echo "<th class=\"ref_head\">$data</th>";
}
else
{
echo "<td>$data</td>";
}
}
echo "</tr>";
if($num == 0)
{
$num++;
}
}
?>
</table>
<table class="table">
<caption>Active Referrers</caption>
<?
$num = 0;
foreach($active_ref_table_arr as $fields)
{
echo "<tr>";
foreach($fields as $data)
{
if($num == 0)
{
echo "<th class=\"ref_head\">$data</th>";
}
else
{
echo "<td>$data</td>";
}
}
echo "</tr>";
if($num == 0)
{
$num++;
}
}
?>
</table>
Try this code:
$csvData = array(
array("1","2","3","4"),
array("2","1","6","6")
);
$fp = fopen('php://memory', 'w+');
foreach ($csvData as $row) {
fputcsv($fp, $row);
}
rewind($fp);
$csvFile = stream_get_contents($fp);
fclose($fp);
header('Content-Type: text/csv');
header('Content-Length: '.strlen($csvFile));
header('Content-Disposition: attachment; filename="file.csv"');
exit($csvFile);
I have looped the data to build the CSV as your code would not produce the result you expect. I have also retrieved the file as a string before outputting - this is just a nicety to add a Content-Length header. I have also - and this is the important bit - called exit to output the data, to prevent any more code being executed any prevent and HTML after this code being output.
If you are using this code and still having a problem, then the code is not being called - you should check any if statements etc that this code is wrapped in.
This is way late but let's hope this unblocks someone.
Use ob_end_clean() to clean out other buffers on the page.
Start with ob_end_clean(); and end with exit;
This way, only the output in between will be written to the file.
Related
Dbfiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=65b310b4b973a7577d4953e01c09a124
Currently I have a table that displays a total count of my data values for each source. I'm getting this value after comparing 2 tables 1 is crm_leads with all my product information and 1 is crm_sources with what sources are the products related to.
Now this is the output:
Now as you can see the total count is shown under each header next to its source. There are 8 cells for each source as seen in the picture. Now these count values are inside a tags which once clicked go to viewall page.
Now here basically I want to show the data of the item that I had clicked. So for example, if I clicked the 163 under Hot status, it takes me to the viewall page and shows me id, source, enquiry_date for all those under status Hot in a table.
So basically it should detect the data for which source and which status is clicked and then accordingly make a statement like this?
select * from crm_leads where lead_source = '.$source.' and lead_status = '.$status.';
Another thing I'm thinking I can do here is put my table inside a form and pass those values as post in my controller class leadstatus which will pass that value to viewall? Not really sure on how to proceed.
Model Class:
function get_statusreport($fdate='',$tdate='')
{
$this->db->select("l.lead_status,crm_sources.title,count(*) as leadnum,l.enquiry_date,l.sub_status");
$this->db->from($this->table_name." as l");
if($fdate !='')
$this->db->where("date(l.added_date) >=",date('Y-m-d',strtotime($fdate)));
if($tdate !='')
$this->db->where("date(l.added_date) <=",date('Y-m-d',strtotime($tdate)));
$this->db->where("lead_status <>",10);
$this->db->join("crm_sources ","crm_sources.id= l.lead_source","left");
$this->db->group_by("l.lead_status,crm_sources.title");
$this->db->order_by("leadnum DESC, crm_sources.title ASC,l.lead_status ASC");
$query = $this->db->get();
$results = $query->result_array();
return $results;
}
Controller Class(leadstatus holds the view for my current table):
public function leadstatus($slug='')
{
$content='';
$content['groupedleads'] = $this->leads_model->get_statusreport($fdate,$tdate);
$this->load->view('crm/main',$main);
$this->load->view('crm/reports/leadstatus',$content);
}
public function viewall($slug='')
{
$content='';
$this->load->view('crm/main',$main);
$this->load->view('crm/reports/viewall',$content);
}
View class:
<?php
$ls_arr = array(1=>'Open',8=>'Hot',2=>'Closed',3=>'Transacted',4=>'Dead');
foreach($groupedleads as $grplead){
$statuses[] = $status = $ls_arr[$grplead["lead_status"]];
if($grplead["title"] == NULL || $grplead["title"] == '')
$grplead["title"] = "Unknown";
if(isset($grplead["title"]))
$titles[] = $title = $grplead["title"];
$leaddata[$status][$title] = $grplead["leadnum"];
}
if(count($titles) > 0)
$titles = array_unique($titles);
if(count($statuses) > 0)
$statuses = array_unique($statuses);
?>
<table>
<tr">
<th id="status">Source</th>
<?php
if(count($statuses) > 0)
foreach($statuses as $status){
?><th id=<?php echo $status; ?>><?php echo $status; ?></th>
<?php
}
?>
<th>Total</th>
</tr>
<?php
if(is_array($titles))
foreach($titles as $title){
?>
<tr>
<?php
$total = 0;
echo "<td>".$title."</td>";
foreach ($statuses as $status) {
$num = $leaddata[$status][$title];
echo "<td><a target='_blank' href='".site_url('reports/viewall')."'>".$num."</a></td>";
$total += $num;
$sum[$status] += $num;
}
echo "<td>".$total."</td>";
$grandtotal += $total;
?>
</tr>
<?php } ?>
</table>
You can include the source and status in the URL like this:
foreach ($statuses as $status) {
$num = $leaddata[$status][$title];
echo "<td><a target='_blank' href='" . site_url('reports/viewall?source=' . $source . '&status=' . $status) . "'>" . $num . "</a></td>";
$total += $num;
$sum[$status] += $num;
}
Then in your controller:
public function viewall($slug = '')
{
$content = '';
$source = $this->input->get('source');
$status = $this->input->get('status');
// Do what you want with $source and $status
$this->load->view('crm/main', $main);
$this->load->view('crm/reports/viewall', $content);
}
so I am making a web site that allows user to read from a xlsx file sheet and download all the data each in a separate pdf here is the code
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);
// Load Composer's autoloader
require 'vendor/autoload.php';
$file_name="";
//index.php
$message = '';
require_once __DIR__.'/../src/SimpleXLSX.php';
echo '<h1>XLSX to HTML</h1>';
if (isset($_FILES['file'])) {
if ( $xlsx = SimpleXLSX::parse( $_FILES['file']['tmp_name'] ) ) {
$filen=$_FILES['file']['tmp_name'];
echo '<h2>'.$xlsx->sheetName($_POST['sh']-1).'</h2>';
echo '<table border=1>';
$dim = $xlsx->dimension();
$num_cols = $dim[0];
$num_rows = $dim[1];
foreach ( $xlsx->rows($_POST['sh']-1) as $k => $r ) {
// if ($k == 0) continue; // skip first row
echo '<tr>';
if ($k == 0) echo '<td>' .$r[ 0 ]. '</td>';
else
echo '<td>' .substr_replace($r[ 0 ],"",strripos($r[ 0 ]," ")). '</td>';
echo '<td>' .$r[ 1 ]. '</td>';
echo '<td>' .$r[ 2 ]. '</td>';
echo '<td>' .$r[ 4 ]. '</td>';
echo'<td>' . $r[ 5 ]. '</td>';
echo'<td>' . $r[ 7 ]. '</td>';
echo'<td>' .$r[ 8 ] . '</td>';
echo '</tr>';
if ($k != 0) // skip first row
{$date = substr_replace($r[0], "", strripos($r[0], " "));
$factname = $r[1];
$name = $r[2];
$email = $r[4];
$phone = $r[5];
$post = $r[7];
$pack = $r[8];
echo $name;
if ($pack == '90') $garanti = '30 jours';
else if ($pack == '190') $garanti = '6 mois';
else if ($pack == '290') $garanti = '12 mois';
else if ($pack == '390') $garanti = '2 ans';
else if ($pack == '490') $garanti = '3 ans';
else if ($pack == '590') $garanti = '5 ans';
sendmail();
echo'<td>telecharger</td>';}
// echo "telecharger";
}
echo '</table>';
echo '</tr>';
}
echo '</table>';
}
else {
echo SimpleXLSX::parseError();
}
if(isset($_POST['charge'])) {
if (isset($_FILES['file'])) {
if ($xlsx = SimpleXLSX::parse($_FILES['file']['tmp_name'])) {
foreach ($xlsx->rows($_POST['sh']-1) as $k => $r) {
if ($k == 0) continue; // skip first row
$date = substr_replace($r[0], "", strripos($r[0], " "));
$factname = $r[1];
$name = $r[2];
$email = $r[4];
$phone = $r[5];
$post = $r[7];
$pack = $r[8];
if ($pack == '90') $garanti = '30 jours';
else if ($pack == '190') $garanti = '6 mois';
else if ($pack == '290') $garanti = '12 mois';
else if ($pack == '390') $garanti = '2 ans';
else if ($pack == '490') $garanti = '3 ans';
else if ($pack == '590') $garanti = '5 ans';
sendmail();
echo "telecharger";
}
}
echo "telecharger";
}
}
echo '<h2>Upload form</h2>
<form method="post" enctype="multipart/form-data">
*.XLSX <input type="file" name="file" />
<input placeholder="sheet number" name="sh" type="number" required>
<input type="submit" value="Parse" />
</form>';
function sendmail()
{
global $name;
global $file_name;
$file_name="";
echo $file_name;
include('pdf.php');
$pdf = new Pdf();
$file_name = "ORDER-".$name . '.pdf';
$html_code = '<link rel="stylesheet" href="bootstrap.min.css">';
$html_code .= fetch_customer_data();
$pdf->load_html($html_code);
$pdf->render();
$file = $pdf->output();
file_put_contents($file_name, $file);
// $pdf->stream($file_name) ->
}
and this is the pdf.php file
<?php
//pdf.php
require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;
class Pdf extends Dompdf{
public function __construct(){
parent::__construct();
}
}
?>
I want to download all the pdfs at the same time but it only downloads the first one and shows me this error
( ! ) Fatal error: Cannot declare class Pdf, because the name is already in use in C:\wamp64\www\vucrm\xl\simplexlsx-master\examples\pdf.php on line 0
I tried to add exit() at the end of sendmail function but this only download the first and shows no other data or errors
can anyone help thanks in advance
You need to use require_once at the top of your script, don't use include inside the function.
// Require this at the top of your file
require_once('pdf.php');
The issue is each time you call the function, it includes the PDF class again and it can only be declared once.
Downloadable PDF files in html link!
To Download PDF from HTML link using PHP with the help of header() function in php.
The header() function is used to send a raw HTTP header.
Sometimes it wants the user to be prompted to save the data such as generated PDF.
Syntax:
http response headers to download any application
header("Content-Type: application/octet-stream");
http response headers to set composition and file to download
header('Content-Disposition: attachment; filename="downloaded.pdf"');
The length of the requested file need to download
header("Content-Length: " . filesize("download.pdf"));
Reads a file and writes it to the output buffer.
readfile('original.pdf');
PHP codes
$file = $_GET["file"] .".pdf";
// We will be outputting a PDF
header('Content-Type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="gfgpdf.pdf"');
$imagpdf = file_put_contents($image, file_get_contents($file));
echo $imagepdf;
HTML codes
<!DOCTYPE html>
<html>
<head>
<title>Download PDF using PHP from HTML Link</title>
</head>
<body>
<center>
<h2 style="color:green;">Welcome To GFG</h2>
<p><b>Click below to download PDF</b>
</p>
Download PDF Now</center>
</body>
</html>
Note: Remember that HTTP header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file or from PHP.
Example 1: Save below HTML file as htmllinkpdf.html and save PHP file as downloadpdf.php
Above example to illustrate concept of downloading PDF file using HTML link.
Downloading file appears to be PDF format but without any content which shows error on opening in any application.
See more here
Here is another simple solution in for loop
I need to attach two tables.
First loop is perfect,
but second For-loop table goes to the Bottom.
I need to attach that bottom table to that previous one.
Can anyone please solve this problem?
Any Solution would be appreciated, so suggest something to solve this.
<?php
include 'pappu.php';
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
$grab=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/USDT');
$json = json_decode($grab, true);
$usd= $json['Data'][3]['AskPrice'];
$grabb=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/USDT');
$jsonss = json_decode($grabb, true);
$dogeusd= $jsonss['Data'][8]['AskPrice'];
$grabsz=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/DOGE');
$jsonsz = json_decode($grabsz);
$grabs=ngegrab('https://www.cryptopia.co.nz/api/GetMarkets/BTC');
$jsons = json_decode($grabs);
echo "<table border=1>";
echo "<th>BTC EXCHANGE</th>";
if($jsons)
foreach ($jsons->Data as $sam){
$market= $sam->Label . "\n";
$link= $sam->AskPrice . "\n";
echo "<tr><td>$market</td>";
$link = number_format($link, 8);
echo "<td>$link" ;
echo '($';
echo number_format($link * $usd, 6) ;
echo ')';
echo "</td></tr>";
}
echo "<th>DOGE EXCHANGE</th>";
foreach ($jsonsz->Data as $sam){
$market= $sam->Label . "\n";
$link= $sam->AskPrice . "\n";
echo "<tr><td>$market</td>";
$link = number_format($link, 8);
echo "<td>$link" ;
echo '($' ;
echo number_format($link * $dogeusd, 6) ;
echo ')';
echo "</td></tr>";
}
echo "</table>";
?>
First set the table headers (<th>), then set the table body if you want all the headers to appear inline.
You can then make arrays for the rows of the two tables and just output for each row.
Note: In case your $btc and $doge arrays have a different amount of rows or are not in the same order you then might have to create a third array by combining the two, then loop over that.
echo '<table border="1">
<tr>
<th colspan="2">BTC EXCHANGE</th>
<th colspan="2">DOGE EXCHANGE</th>
</tr>';
// prepare the rows
$btc = array();
$doge = array();
if($jsons)
{
foreach ($jsons->Data as $sam)
{
$number = (float) $sam->AskPrice;
array_push($btc, array($sam->Label, number_format($number,8) ));
}
foreach ($jsonsz->Data as $sam)
{
$number = (float) $sam->AskPrice;
array_push($doge, array($sam->Label, number_format($number,8) ));
}
// assuming count($btc) and count($doge) are the same
for($i=0; $i< count($btc); $i++)
{
echo '<tr>
<td>'.$btc[i][0].'</td>
<td>'.$btc[i][1].' ($'.number_format($btc[i][1] * $usd, 6).')</td>
<td>'.$doge[i][0].'</td>
<td>'.$doge[i][1].' ($'.number_format($doge[i][1] * $usd, 6).')</td>
</tr>';
}
}
echo '</table>';
?>
You have two <th> cells which should be in a table row <tr>:
echo "<th>BTC EXCHANGE</th>";
and
echo "<th>DOGE EXCHANGE</th>";
Change your code to:
echo "<tr><th>BTC EXCHANGE</th></tr>";
and
echo "<tr><th>DOGE EXCHANGE</th>";
I have a large table with an unknown amount of columns that I want to be able to export to MS Excel via a download link. I have done this before with no issues. However, that was when I had a known number or columns. I currently am able to successfully send data to an Excel file. The table headers display correctly across the top of the table. The problem is with the data. Instead of placing the data across the page in the correct columns, it is putting it all in the first column. Here is part of my code:
while($row = mysql_fetch_row($result))
{
// Loops through the results
for($i=0; $i < $num_cols; $i++)
{
// Prints out the data in a table cell
echo("<Td class='data'>$row[$i]</Td>");
$FileRecord = Array($row[$i]);
$exportFile->Export_Record($FileRecord);
}
}
Normally I do $FileRecord = Array($row[0], $row[1], ..., $row[n]) and everything works great, but I am not sure how to do that if I don't know how many columns there are. Any help would be great!
I am not using any library. $exportFile is from a function that I am using. It looks like this:
class CSV_File {
private $out='';
private $name='';
private $column_names="";
private $count = 0;
//Creates the file name and the header columns
function __Construct($buf, $names) {
$GLOBALS["name"] = $buf;
$GLOBALS["column_names"] = ($names."\n");
}
public function Export_Record($array) {
if (!is_array($array))
throw new Exception("NOT AN ARRAY");
for ($i = 0; $i <= count($array); $i++) {
$GLOBALS["out"] .= $array[$i];
if ($i < count($array)-1) {
$GLOBALS["out"] .= ",";
}
}
$GLOBALS["out"] .= "\n";
$GLOBALS["out"]++;
}
public function ExportButton($align) {
$output = $GLOBALS["out"];
$filename = $GLOBALS["name"];
$columns = $GLOBALS["column_names"];
if ($align == null)
$align = "align";
echo(" <$align><form name=\"export\" action=\"export.php\" method=\"post\">
<button type=\"submit\" style='border: 0; background: transparent; font-size: 12px;font-weight:bold;'>
<img src = 'images/icon_csv.png' width = '16' height ='16' alt ='Download Data'> Download</button>
<input type=\"hidden\" value=\"$columns\" name=\"csv_hdr\">
<input type=\"hidden\" value=\"$filename\" name=\"fileprefix\">
<input type=\"hidden\" value=\"$output\" name=\"csv_output\">
</form></align>");
}
}
And then export.php looks like this:
if (isset($_POST['csv_hdr']))
{
$out .= $_POST['csv_hdr'];
$out .= "\n";
}
if (isset($_POST['csv_output']))
{
$out .= $_POST['csv_output'];
}
if (isset($_POST['fileprefix']))
{
$fname .= $_POST['fileprefix'];
}
//Now we're ready to create a file. This method generates a filename based on the current date & time.
$filename = $fname."_".date("Y-m-d_H-i",time());
//Generate the CSV file header
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
//Print the contents of out to the generated file.
print $out;
//Exit the script
exit;'
That's not an Excel table. It's an html table that you just happen to be feeding into Excel.
Your problem is that you're not starting a new table row for every record you're fetching, so everything just becomes a new cell in the first row.
You need something like
while($row = mysql_fetch_assoc($result)) {
echo '<tr>';
foreach($row as $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}
I have this code: messages.php
if (count($row) > 0)
{
foreach ($row as $r)
{
//some code setting variables
if ($opened_once >= 1)
{
}
else
{
echo "<tr>";
echo '<td><a class="red_link" href="'.ADDRESS.'view_message.php?id='.$r['id'].'" id= "subject_id" ><span id = "subject">'.$r['subject'].'</span></a></td>';
echo '<td id = "unique_code1">'.$uniqueCode1.'<span class="pink_text" id = "unique_code2">'.$uniqueCode2.'</span><span id = "unique_code3">'.$uniqueCode3.'</span></td>';
echo "</tr>";
}
}
I need to update $r['id'], $r['subject'], $uniqueCode1, $uniqueCode2, $uniqueCode
My jQuery code:
<script>
$(document).ready(function()
{
refresh();
});
function refresh()
{
$.post('getMessageDetails.php', function (json) {
$("#subject").html(json.subject);
$("#subject_id").html(json.subject_id);
$("#unique_code1").html(json.unique_code1);
$("#unique_code2").html(json.unique_code2);
$("#unique_code3").html(json.unique_code3);
});
window.setTimeout(refresh,30000);
}
</script>
Then I have newMessageCnt.php
<?php
<?php
header('Content-Type: application/json; charset=utf-8');
include('header_application.php');
$limit = 15;
if(!isset($_GET['page']))
$page = 1;
else
$page = $_GET['page'];
$from = (($page * $limit) - $limit);
$row = $obj_clean->getMessages($_SESSION['user_id'], $from, $limit);
if (count($row) > 0)
{
foreach ($row as $r)
{
$codeLength = strlen($r['unique_code']);
$codeLength = strlen($r['unique_code']);
$firstPartLength = $codeLength - 5;
$uniqueCode3 = substr($r['unique_code'], -2);
$uniqueCode2 = substr($r['unique_code'], -5, 3);
$uniqueCode1 = substr($r['unique_code'], 0, $firstPartLength);
$message_id = $r['id'];
$subject = $obj_clean->getMessageDetails($message_id);
$opened_once = $obj_clean->getOpenedOnce($message_id);
if ($opened_once >= 1)
{
$array['subject'] = $r['subject'];
$array['subject_id'] = $r['id'];
$array['unique_code1'] = $uniqueCode1;
$array['unique_code2'] = $uniqueCode2;
$array['unique_code3'] = $uniqueCode3;
}
}
}
echo json_encode($array);
exit();
?>
?>
I call this .php somewhere else as well where I just want the value of echo $obj_clean->getUnopenedMessagesCount($_SESSION['user_id']);
But from my messages.php I want
echo '<td><a class="blue_link" href="'.ADDRESS.'view_message.php?id='.$r['id'].'">'.$r['subject'].'</a></td>';
echo '<td>'.$uniqueCode1.'<span class="pink_text">'.$uniqueCode2.'</span>'.$uniqueCode3.'</td>';
I'm not sure if I'm doing this right, some advice please?
$.post('ajax_call.php', function (json) {
$("#subject").html(json.subject);
$("#unique_code").html(json.unique_code);
});
//ajax_call.php
<?php
$array['subject']='bla-bla';
$array['unique_code']='1231312';
header('Content-Type: application/json; charset=utf-8');
echo json_encode($array);
exit();
Better would be to have your PHP return an object containing the values you want as properties. This can be sent back to the browser using JSON. Your client-side code see this as an object and can extract the properties and populate the HTML. This separates your presentation (VIEW) from your data (MODEL).
EDIT: Exactly as #TROODON has answered.