Note that there are some explanatory texts on larger screens.

plurals
  1. POSending a PHP variable to a new file on button onClick
    text
    copied!<p>I am trying to allow download of results (a table) generated when a users searches our inventory. I want to be able to click on a button to download the results into a CSV file. I am able to generate the CSV file if I add the PHP code directly after I run the query. However, I need this button to be in a different place on the page and thus I want to be able to call this function sending in the query results rather than directly after the search.</p> <p>If I do this then I am able to generate the file.</p> <pre><code>function output_csv ($data) { $filename = "exportfile.csv"; $handle = fopen($filename, 'w+'); fputcsv($handle, array('UserID','UserName')); foreach($row = $data-&gt;fetch(PDO::FETCH_ASSOC)) { fputcsv($handle, array($row['UserID'], $row['UserName'])); } fclose($handle); } </code></pre> <p>I know PHP is a server side so I can't call this function on the onclick if it is on the same page as the button. I was thus thinking I should put this function in a separate file which I can call from the onclick. But I cannot figure out a way to pass the $data (query results), it keeps on telling me the variable cannot be converted to a string.</p> <pre><code>$file_array=$db-&gt;prepare("SELECT UserID, UserName FROM UserProfile"); $file_array-&gt;execute(); &lt;button type="button" onclick="download_file.php?pass_array=&lt;?php echo $file_array; ?&gt;)"&gt;Click Me&lt;/button&gt; </code></pre> <p>My problem is thus that I cannot figure out how to send the results of the query to the output_csv function in my page or another page so that they can be written to the file.</p> <p>Thanks,</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload