I have followed the explanation given here to write the query result to a file.
But in this case I have to open and write the files headers first. Then keep writing/appending the query results one by one for multiple queries. This appending part I have written as a function. The problem that my script write the file with the headers (from the first part) only, it does not follow the fputcsv commands present in the function when it is called. Can you help me in solving this.
Here is my code to first open the file:
<?php
$fp = fopen('php://output', 'w');
$headers = array("Index","Gene_symbol","Gene_Name","Human_entrez","Rat_entrez","Mouse_entrez","DbTF","PMID");
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.txt"');
fputcsv($fp, $headers,chr(9));
header('Pragma: no-cache');
header('Expires: 0');
?>
Then the query part is somewhat like this (I have multiple of such query parts each one calling the same function) :
<?php
if (is_numeric($sterm))
{
$query="select * from tf where entrez_id_human=$sterm || entrez_id_rat=$sterm || entrez_id_mouse=$sterm";
$result=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result)==0)
{echo "<tr><td align='center' colspan=6> $sterm not found! </td> </tr>";}
elseif (mysql_num_rows($result)>0)
{result_disp($result);}
}
?>
then writing the result to file via a function is here:
<?php
function result_disp($results)
{
if($fp && $results)
{
while ($rows = mysql_fetch_row($results))
{
fputcsv($fp, array_values($rows),chr(9));
} die;
}
}
And finally closing the file at end of script
fclose($fp);
?>
Thanks
Your first problem is that your file handle does not have scope within the function. The best way in my opinion is to pass it into the function:
....
elseif (mysql_num_rows($result)>0)
{result_disp($result, $fp);}
....
function result_disp($results, $fp)
{
if($fp && $results)
{
while ($rows = mysql_fetch_row($results))
{
fputcsv($fp, array_values($rows),chr(9));
} //DO NOT PUT "die()" HERE
}
}
Your second problem is the "die()" statement inside the function. The purpose of "die()" is to stop the script entirely. It is PHP suicide. So, if you leave it in, your script will halt at the end of the first call of result_disp. That means not only would you never reach fclose($fp), you'll never reach any other call to result_disp.
Your third problem is that you are using mysql_* functions. These are deprecated (no longer in use) for several reasons. I have personal experience with database connection freezes caused by it. You should switch to mysqli or PDO.
Related
Im building an app using PHoneGap as the compiler so using HTML5, CSS, JQuery, AJAX etc. Ive manage to get AJAX to GET all the rows from the Database perfectly well, as I have to use .HTML extension on my files I'm struggling to be able to link through to specific DB record. I can do this perfectly in PHP. Im struggling with the HTML part.
Here is my AJAX Loader to get all Rows from DB
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call ...
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MY-URL.COM/videos-mysql.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'POST', //Makes sense only if you passing data
success: function(answer) {
jQuery('#videos-modules').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
error: function() {
//unknown error occorupted
inProcessVideos = false;//Queue is free, guys ;)
}
});
}, 500 );
And here is the contents of the PHP File that renders all the Results from the Database. This part displays the content perfectly.
<?php
include ("../config/mysqli_connect.php");
$sql = ("SELECT * FROM videos");
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "
<a href='" . $row["id"]. "'>
<div class='video-module'>
<div class='video-thumb'><img src='https://MY-URL.COM/thumbs/" . $row["video_thumb"]. "'></div>
<div class='video-thumb-details'>
<div class='video-thumb-title'> " . $row["id"]. " - " . $row["video_title"]. "</div>
" . $row["publisher_name"]. "
</div>
</div></a>
";
}
} else {
echo "0 results";
}
?>
After the ECHO statement I would normally put something like video-Profile.php?id=$id and it would go to that page and pull in that record from the Database.
However now that I have to do it only in HTML, and im assuming AJAX, how to I achieve this.
Here is the PHP and the MYSQL Query to GET the specific record from the Database. Its currently in MYSQL, I will convert it to MYSQLi once I've got it working and got my head around it.
<?php
// Use the URL 'id' variable to set who we want to query info about
$id = ereg_replace("[^0-9]", "", $_GET['id']); // filter everything but numbers for security
if ($id == "") {
echo "Missing Data to Run";
exit();
}
//Connect to the database through our include
include_once "../config/connect_to_mysql.php";
// Query member data from the database and ready it for display
$sql = mysql_query("SELECT * FROM videos WHERE id='$id' LIMIT 1");
$count = mysql_num_rows($sql);
if ($count > 1) {
echo "There is no user with that id here.";
exit();
}
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$video_title = $row["video_title"];
$video_thumb = $row["video_thumb"];
$publisher_name = $row["publisher_name"];
$video_directory = $row["video_directory"];
$video_path = $row["video_path"];
$upload_date = $row["upload_date"];
$video_views = $row["video_views"];
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php echo ("$id");?> - <?php echo ("$video_thumb");?>
</body>
</html>
I know this works if I'm running PHP files, and my server is set to PHPv5.3., but before I make it live, it will be sorted to MYSQLi and run on PHP7???
Im looking for inspiration to get this to function via HTML only files.
thanks for your help everyone.
This is a pretty brutalistic way of doing this - typically you'd return JSON or similar from the PHP and then process this into the HTML elements within your JS. But for this case you can do this:
//within call
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id
}) // This allows you to search your child elements and pick them based on criteria
jQuery('#videos-modules').html(contents); // now assign the remaining elements into your html as before
},
I have Tried this but i cant seem to find out how to Run a Console Log as it is Run on iOS iPad at the moment. Can not get it to render in the Browser.
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MYURL.COM/appFiles/tablet/video-profile.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'GET', //Makes sense only if you passing data
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id;
});
jQuery('#videoProfile').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
});
}, 500 );
Struggling with this, i've looked at all the JQuery, AJAX MySQL web sites i can find including W3Schools, Jquery.com and many others. Just can not get it to pass the ID to the PHP file to get the Record from the DB via AJAX.
My Links in the first JQuery AJAX Call are:
<a href='video-Profile.html' data='".$row["id"]."' value='".$row["id"]." '>Some HTML STUFF/Images/Text etc</a>
I can get the ID and the First AJAX Call to show ALL the rows in the DB Table. Now just need to show Record by ID. This is what i cant get my head around. And it must be in .HTML Page as its an App compiled via PhoneGap. I know im repeating my self, Just not to sure if im making my point clear. Thanks for the help in advance.
I have a ActiveForm which I use to get some data from and when I click the send button it will run the model (in this case a csv file generator) but the refresh is not working, when I remove the method it will refresh.
After some testing it seems that fputcsv() will stop the script, so that everything that comes after this will not run.
view
public function actionIndex()
{
$model = new Export();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$fields = Yii::$app->request->post('Export');
\backend\models\Export::generate();//this prevents the refresh
Yii::$app->session->setFlash();
return $this->refresh();
} else {
return $this->render('index' , ['model' => $model]);
}
}
model
static public function generate()
{
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="sample.csv"');
header("Pragma: no-cache");
header("Expires: 0");
$data = [array comes here];
$fp = fopen('php://output', 'w') or die("Unable to open file!");
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
foreach ( $data as $line ) {
fputcsv($fp , $line , ';' );
}
stream_get_contents($fp);
fclose($fp);
}
Controller::refresh() uses Location header to reload page. Since headers need to precede the content, you cannot add new header after content was sent. Your Export::generate() method sends content, so you cannot add any header after that, thus $this->refresh() do not work.
Prior to Yii 2.0.14 there was a bug and framework simply ignored that you're trying to send header after content has been send. If you upgrade Yii, you should get "nice" Exception in this case.
If you're trying to display nice page after downloading file, your approach is incorrect. You can't really return file and then redirect to different page. You should first display nice HTML page and inside of it redirect user to download page (for example by using <meta http-equiv="refresh" content="0; url=http://example.com/" /> in head or creating hidden form and submitting it by JavaScript). After downloading the file user will stay at this nice page, so from UX perspective everything should be OK.
The SWF is located on a web server. I am calling the function using this code in AS3...
myPDF.save(Method.REMOTE, "http://www.example.com/generator/createpdf.php",
Download.ATTACHMENT, "line.pdf");
Here is my PHP script located on the server...
$method = $_GET['method'];
$name = $_GET['name'];
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
// get bytearray
$pdf = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
header('Content-Type: application/pdf');
header('Content-Length: '.strlen($pdf));
header('Content-disposition:'.$method.'; filename="'.$name.'"');
echo $pdf;
} else echo 'An error occured.';
It used to work, but stopped a while back. Any help would be greatly appreciated.
1) This stopped working for me as well, until I added the following -
if(!$HTTP_RAW_POST_DATA){
$HTTP_RAW_POST_DATA = file_get_contents(‘php://input’);
}
2) I also patched /src/org/alivepdf/pdf/PDF.as::save() per this post enter link description here
I am trying to pass a variable from one PHP page to another PHP page, which will trigger an Excel download. However, I cannot figure out how to pass the variable and still have the download trigger. I understand that my PHP page which creates the Excel file cannot have any variables passed to it, or the download will not trigger.
For example, I would like to do the following (very simple example):
variable.php
<?php
$date = '2012-02-15';
echo '<input type="text" id="date" value="'.$date.'"/>';
echo '<span onclick="excelDownload()">Click</span>';
?>
passing.js
function excelDownload(str)
{
Ajax...
var date = document.getElementById('date').value;
var queryString = "?date=" + date;
xmlhttp.open("GET", "excel.php" + queryString, true);
Ajax....
}
excel.php
<?php
Connect to database...
$date = $_GET['date'];
$file = "Names: ";
$result = mysql_query("SELECT * FROM Something WHERE date_field = '$date'");
$data = mysql_fetch_array($result);
$file.= $data['names']." ";
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=names.xls");
header("Pragma: no-cache");
header("Expires: 0");
print $file;
?>
Unfortunately, the $_GET[date'] variable causes the excel.php to not download. I have been able to get away with writing static MySql queries within the excel.php page, so I do not have to pass any variables. However, I now have the need to create dynamic excel downloads, but I am not strong enough in php to figure out my options. On a side note, I use Ajax and do not utilize "submit". Will this be a problem?
I figured out my problem and wanted to share my findings to close out this question. Basically, I should have been more detailed in my question. My Ajax function needed some tweaking so that the variable would pass and allow the headers to trigger a download.
I was using the following in my Ajax function:
Ajax...
{
if (xmlhttp.readyState == 4)
{
//nothing to allow download to trigger
}
}
var date = document.getElementById('date').value;
var queryString = "?date=" + date;
xmlhttp.open("GET", "excel.php" + queryString, true):
xmlhttp.send(null);
However, I should have used this:
Ajax...
{
if (xmlhttp.readyState == 4)
{
window.location = "excel.php" + queryString;
}
}
var date = document.getElementById('date').value;
var queryString = "?date=" + date;
xmlhttp.open("GET", "excel.php" + queryString, true):
xmlhttp.send(null);
While I was thinking my problem had to do with output before header(), the real issue was passing the variable.
I need to bootstrap Drupal. I have a php-file with all my functions and in one of those functions, I need to use a Drupal function which is located in the bootstrap.inc file.
Structure of the server:(d) drupal (sd)includes (f)bootstrap.inc(d) scripts (sb)functions (f) functions.php
So I need to include in a self-written function the "variable_set" function, located in bootstrap.inc.
A little piece of the function my college wrote (I'm terribly sorry, but I don't know how to format php on the forum. If someone does, please let me know so I can edit this mess):
function readxml()
{
echo "<br/>READING...<br/>";
$file = './config.xml';
$xml = simplexml_load_file($file);
if($xml !== false)
{
foreach($xml->config->children() as $item){
$name = $item->getName(); // GETS CHILDREN UNDER 'CONFIG'
switch($name)
{
case 'website':
foreach($xml->config->website->children() as $kid){
$childname = $kid->getName();
switch($childname)
{
case 'theme':
if(inserttheme($kid)or die ('failed to insert theme<br/>')){
echo 'theme is installed.<br/>';}
break;
case 'slogan':
if(insertslogan($kid)or die('failed to insert slogan<br/>')){
echo 'slogan is installed.<br/>';}
break;
case 'sitename':
if(insertname($kid)or die('failed to insert name<br/>')){
echo 'website name is installed.<br/>';}
break;
}
}
break;
`
So, somewhere in the theme/slogan/name section, I have to call the variable_set function which is located in the bootstrap.inc file.
Somewhere I found this (again sorry for the non-formated text):
$drupal_directory = "/home/httpdocs/drupal"; // wherever Drupal is
$current_directory = getcwd();
chdir($drupal_directory);
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
chdir($current_dir);
return;
I included it both in my function.php as well as in my final php-file (where all the functions are called) but no result... What am I doing wrong?
That code you found looks about right, what is exactly is "no result", are you getting errors or nothing or...? Also, where did you put it exactly? (If it is not in a function, you need to remove the last line (return))
Also, the proper way to fix this would be to integrate your custom code as a Drupal module, then you don't have to worry about stuff like this: http://drupal.org/developing/modules
Or if it is a CLI script, expose it as a drush command: http://drupal.org/project/drush
Answer to the question, just include the file inside the Drupal folder!