Reputation: 1351
I am trying to have my mysql database that is displayed on my webpage be exported to a csv on a button click, however it is not functioning as expected. I am attempting to do the following on the click of the export button, but when you click the Export CSV button it goes to a page "url/export.php" and gives an "error page does not exist webpage"
export button definition:
<div class="topnav">
<form method="post" action="export.php">
<input type="submit" name="export" value="CSV Export" class="btn btn-i"
<a class="active" href="#export">Export to CSV</a>
</form>
<div class="search-container">
<form action="/action_page.php">
<input type="text" placeholder="Search.." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
</form>
</div>
</div>
export.php code:
<?php
//export.php
if(isset($_POST["export"])) {
$connect = mysqli_connect("localhost", "root", "password", "dbName");
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen("php://output", "w");
fputcsv($output, array('Username', 'Password', 'PhysicianID'));
$query = "SELECT * FROM Users";
$result = mysql_query($connect, $query);
while($row = mysqli_fetch_assoc($result)) {
fputcsv($output, $row);
}
fclose($output);
}
?>
Upvotes: 0
Views: 45
Reputation: 10069
You are fundamentally misunderstanding how server-side and client-side code interact.
A PHP script just outputs everything it comes across until a PHP opening tag is come across (<?php
). Then code is interpreted as PHP. Processing is done, perhaps some more output is made. After a close PHP tag (?>
) things are just output again (subject to flow control structures and such).
PHP has no idea what Javascript is, and vice versa.
Your PHP script runs when the page is requested. It outputs an HTML <script>
tag, and some Javascript. And at the same time as this HTML is generated, all that code in your <?php
delimiters is running on the server. Not on a click event -- right when the page is generated.
If you want server-side code to run in response to a client-side event, you'll need to make a request (either via Javascript or via a new page fetch) to a server-side script. That script is where this database-access code should be.
For example, the button might be on an HTML page like this:
<form action="get-csv.php" method="POST">
<button class="active">Export to CSV</button>
</form>
This can be on a plain HTML page, or output by another PHP script.
Now put your code to export data from the database in get-csv.php
.
Upvotes: 1