I want to create a PDF using HTML, PHP, and MySQL and I want a new page every time a new row is fetched and then generate a combined PDF for all the pages created.
How can I achieve this?
<?php
$count=0;
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con, "electricity");
$result = mysqli_query($con, "SELECT acct, name, address, amount FROM newtable");
while($row = mysqli_fetch_array($result))
{
?>
<html>
<body><pre>
श्री: <?php echo $row['name'];?><br>
पता: <?php echo $row['address'];?>
ACCNO :- <b><?php echo $row['acct'];?></b>
Amount : <b><?php $val=$row['amount']+25; echo $val;?></b>
</pre>
</body>
</html>
<?php
}
mysqli_close($con);
?>
I used FPDF many times and it allows you to do whatever you want. Have more info here for doc & download link : http://www.fpdf.org/?lang=en
I need to display a list of results form a survey on a PHP page then export them to a CSV file. The list also acts as a summary that can be clicked thorugh to the full result.
I have all that sorted but now I need to have the CSV export by a check bx selection so that we dont need to download the entire databse each time just the ones we need.
My code so far below.
<div class="resultsList">
<h1>PEEM Results List</h1>
<a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
<!-- Export CSV button -->
<h3 class="resultsbydate">All results by date</h3>
<div class="resultsListHeader">
<div class="clientidTab">Agency</div>
<div class="clientidTab">Family ID</div>
<div class="clientidName">Name</div>
<div class="clientidTab">Date</div>
<div class="clientidTab"></div>
</div>
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<div><input type=\"checkbox\" name=\"xport\" value=\"export\"><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent’s Review</strong></a></span>";
echo "<span><strong>View Results</strong></span>";
echo "</div>";
}
?>
</div>
</div>
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query1 = mysql_query("select * from results where survey_id=$id", $connection);
while ($row1 = mysql_fetch_array($query1)) {
?>
<?php
}
}
?>
<?php
mysql_close($connection); // Closing Connection with Server
?>
And the downloadcsv.php
<?php
$conn = mysql_connect("localhost","username","password");
mysql_select_db("databasename",$conn);
$filename = "peem_results.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
$query = "SELECT * FROM results";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
?>
Any help with this would be great, cheers
Updated with a screenshot of what I am trying to achieve
The initial result set needs to be wrapped in a form which POST to the next page.
The Checkbox must send an array of ids to the export script.
<input type='checkbox' name='xport[]' value='ID_OF_THE_ROW_HERE'>
The [ ] after xport means that $_POST['xport'] will be an array of values.
The export page can collapse that array of ids into a comma separated string and to be used the query:
SELECT * FROM results WHERE id IN (4,7,11,30)
<form method="POST" action="downloadcsv.php">
<h1>PEEM Results List</h1>
<a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
<!-- Export CSV button -->
<h3 class="resultsbydate">All results by date</h3>
<div class="resultsListHeader">
<div class="clientidTab">Agency</div>
<div class="clientidTab">Family ID</div>
<div class="clientidName">Name</div>
<div class="clientidTab">Date</div>
<div class="clientidTab"></div>
</div>
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<div><input type='checkbox' name='xport[]' value='{$row['client_id']}'><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent’s Review</strong></a></span>";
echo "<span><strong>View Results</strong></span>";
echo "</div>";
}
?>
</div>
</form>
Change $row['client_id'] to the correct value
Then in the export script:
<?php
/*
Expecting $_POST['xport'] array of row ids
*/
if( !isset($_POST['xport']) OR !is_array($_POST['xport']) ) {
exit('No rows selected for export');
}
$conn = mysql_connect("localhost","username","password");
mysql_select_db("databasename",$conn);
$filename = "peem_results.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
//Cast all ids to integer
$ids = $_POST['xport'];
array_walk($ids, function(&$value, $key) {
$value = (int)$value;
});
$ids = implode(', ', $ids);
$query = "SELECT * FROM results WHERE id IN ($ids)";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
?>
So if I'm getting this correctly, you just need to be able to check checkboxes to select the databses ($rows) you want to insert into the csv file....
Every checkbox that you checked will be in the $_POST variable, so:
1st you make an array with all the names of checkbox options (databases), for example
$all_db = ['database1', 'database2', 'database3'];
2nd you loop through each of the values in $all_db and check if they exist in the $_POST array, if they do, then you can export the row
foreach( $all_db as $db_check ) {
if ( array_key_exists( $db_check, $_POST ) {
// EXPORT TO CSV
}
}
Don't forget ! This means the "name" attribute of the checkbox should be the name of the database.
If you don't want to have a static list of databases (i.e. there is a possibillity of them having different names in the future / there will be moreor maybe less etc then let me know i can edit my answer if needed :) )
( If you use the $_GET variable, then you can do the same thing just change $_POST to $_GET)
Know though that $_GET comes over as a bit amateuristic for the enduser if he gets a thousand variables in his URL,
$_POST is often a better alternative since it is hidden and cleaner for the enduser...
EDIT: UPDATING ANSWER (SEE COMMENT)
So basically you need people to be able to choose what rows they export from you dB...
First of all this means we need a unique ID for each row,
This can either be a column used solely for that (i.e. ID column with auto increment and unique attribute)
Or this can be a column you already have, just make sure it's a unique column so we don't get dupliate values (you'll see why below)
Then we give the value of this unique ID column to the checkbox's "name" attribute, and using jquery / php we append / prepend a static string...
For example, using your family ID:
"rownumber_" + $family_ID
This gets us (again using your example) :
$_POST[] = ['rownumber_123456' => 1, 'rownumber_0000000' => 1, .....]
So then in your PHP file you just do the following to add the correct lines to your CSV:
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['your_row_id'], $_POST) {
fputcsv($fp, $row);
}
}
-- Again using your example with family_ID : --
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['family_ID'], $_POST) {
fputcsv($fp, $row);
}
}
EDIT: Updating answer for comment no.2
So little sidenote if you are going to loop through html using php
(i.e. loop trhough db rows and print them out in an orderly fashion)
Then you propably want to use the ":" variants of the loops,
While() :
for() :
foreach() :
if () :
.....
These variants allow yu to close the php tag after the ":" and whataver html / css / php / jquery you put in the condition / loop will be executed like normal...
For example you can do :
<ul>
<?php foreach ($row as $columnkey => $columnvalue): ?>
<img src="whateveryouwant"?>
<li class="<?php echo $columnkey;?>">This is my value: <?php echo $columnvalue; ?></li>
<?php endforeach; ?>
</ul>
When you do it this way it's much cleaner and you won't have any problems using double quatation signs and all that stuff :)
So using that method here is how your displayed list would look like in code:
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) :
?>
<div>
<input type="checkbox" name="<?php echo $row['family_id']; ?>" value="export">
<span><?php echo $row['client_id']; ?></span>
<span><?php echo $row['family_id']; ?></span>
<span><?php echo $row['firstname'] . " " . $row['lastname']; ?></span>
<span><?php echo date("d F Y",strtotime($row['peemdate']); ?></span>;
<span>
<a class="parents-button" href="peem-parent-repsonses.php?id=<?php echo $row['survey_id']; ?>">
<strong>Parent’s Review</strong>
</a>
</span>
<span>
<a href="peem-repsonses.php?id=<?php echo $row['survey_id']; ?>">
<strong>View Results</strong>
</a>
</span>
</div>
<?php endwhile; ?>
</div>
Like this the checkbox will get the name of the family ID, and so in your csv.php you can use this code :
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['family_ID'], $_POST) {
fputcsv($fp, $row);
}
}
Since now it will check for each row wether the family ID of the SQL row is posted as a wanted row in the $_POST variable (checkbooxes) and if not it won't export the row into the csv file ! :)
So there you go ^^
EDIT 3: Troubleshooting
So there are a couple of things that you do in this function,
the form,
Do the checkboxes in your html form have the family_ID in their name attribute ?
(i.e. <input type="checkbox" name="<?php echo $row['family_id']; ?>".... check if the name attribute is really filled )
you post stuff from a form, (your checkboxes and stuff)so let's see what actually gets posted,
die(print_r($_POST)); - This means you want php to die after this line (stop working at all), then print out a variable as is (sort of xml format you'll see)
So then you will get a whole bunch of information, if you want to see this information in a nicely formated way, just right click inspect element on it :)
Then see how your checkboxes are coming out of the $_POST variable,
(they should have the family_ID as a key and a value of 1)
If that's all ok, then check your row['family_ID'] variable see if the family_ID is filled correctly, do the same with your whole $row variable, in fact check every variable you use in csv.php and then check why the key does not exist in the array you are searching for :)
Also dont forget to check that you filled the array_key_exists( has a key FIRST and an array[] LAST )
I can't help you directly with this , since this will propably be a faulty variable or a mistake in your form so try to find this yourself, if still nothing , post these variables values:
$_POST
$row
and the full HTML of your form
I am using phpmyadmin and had mySQL database working with my php until I started adding foreign key constraints. Then all of the sudden it stopped working. Now I'm backtracking to the very beginning when I ran my first query, but it still will not work (even though it used to). When I call for the mysql_error() nothing appears.
It seems so simple but I do not know what is going wrong. I even deleted out all of the tables from my database except the subjects table.
manage_content page (which should read my table):
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/db_connection.php");?>
<?php require_once($_SERVER['DOCUMENT_ROOT']."/includes/functions.php");?>
<?php include($_SERVER['DOCUMENT_ROOT']."/includes/header-home.php");?>
<?php
// 2. Perform database query
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
confirm_query($result);
?>
<div id="main">
<div id="navigation">
<ul class="subjects">
<?php
// 3. Use returned data (if any)
while($subject = mysqli_fetch_assoc($result)) {
// output data from each row
?>
<li><?php echo $subject["first_name"] . " (" . $subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
</div>
<div id="page">
<h2>Manage Content</h2>
</div>
</div>
<?php
// 4. Release returned data
mysqli_free_result($result);
?>
<?php include($_SERVER['DOCUMENT_ROOT']."/includes/footer.php");?>
Functions page:
<?php
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed: " . mysql_error());
}
}
?>
Please help! I'm new and I know this is incredibly simple. I just don't know what I'm missing!
Because when you do query you call mysqlI_query() function, but when you wanna get error, you do it with mysql_query(), try to change that!!
mysqli_error()
Echo 'Hello programmers' ;
I'm scratching my head about a pair of drop down menus. They are supposed to display all strings from the ename and mid rows. However this isn't happening and the drop down is only displaying one result from each row. There are multiple strings of test data in the actual rows.
I have some code here and perhaps you could lend a hand. Let me explain.
First off these are the methods from class dbme. To keep the clutter down the second function is exactly the same, except the SQL query for getResult() is obviously different (SELECT * from member as opposed to memberevent)
function openDB() {//creating database connection
$conn = mysqli_connect("localhost", "root", "", "mydb");
if (!$conn) {
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
function getResult($sql){
$result = mysqli_query($this->conn , "SELECT * from memberevent" );
if ($result) {
return $result;
} else {
die("SQL Retrieve Error: " . mysqli_error($this->conn));
}
}
Second, this is the web-side data.
$db1 = new dbme();
$db1->openDB();
$sql="select mid from member";
$result=$db1->getResult($sql);// get the ids from the tables for the select
$sql1="select ename from event";
$result1=$db1->getResult($sql1);// get the ids from the tables for the select
if (!$_POST) //page loads for the first time
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" onsubmit="return validateForm( );">
Select Member ID: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<br />
Select Event name : <select name="ename">
<?php
while($row = mysqli_fetch_assoc($result1))
echo "<option value='{$row['ename']}'>{$row['ename']} </option>";
?>
</select>
<br />
I have a sneaking suspicion that a variable is getting over written, OR an extra loop is needed somewhere. But I'm not really sure, thus I post this question for advice.
Thanks.
You need to iterate through your results inside your getResults() function, otherwise you will always only get one row.
You are passing in the SQL but never using it:
Change
function getResult($sql){
$result = mysqli_query($this->conn , "SELECT * from memberevent" );
To
function getResult($sql){
$result = mysqli_query($this->conn , $sql );
I am beginner to PHP and mySQL. I am creating a navigation trough my database. I have two tables set up one is the main nav items and one is the sub nav items. They are connected by the subject_id. I am using a loop to display them. The first table displays and the second table leaves space for where the information should be but it does not show up. I think it must be something in the SQL settings but I have no idea. Here is my code(i know the database is connected):
<?php require_once("includes/connection.php") ?>
<?php require_once("includes/functions.php") ?>
<?php include("includes/headder.php") ?>
<table id="structure">
<tr>
<td id="navigation">
<ul class="subjects">
<?php
$subject_set = mysql_query("SELECT * FROM subjects", $connection);
if(!$subject_set){
die("database query failed: " . mysql_error());
}
while ($subject = mysql_fetch_array($subject_set)) {
echo "<li>" . $subject["menu_name"] . "</li>";
$page_set = mysql_query("SELECT * FROM pages WHERE subject_id = {$subject["id"]}", $connection);
if(!$page_set){
die("database query failed: " . mysql_error());
}
echo "<ul class=\"pages\">";
while ($page = mysql_fetch_array($page_set)) {
echo "<li>" . $page["menu_name"] . "</li>";
}
echo "</ul>";
}
?>
</ul>
</td>
<td id="page">
<h2>Content Area</h2>
</td>
</tr>
</table>
<?php include("includes/footer.php") ?>
Since you mentioned that white space is showing where the data should be, it appears that rows are indeed found. Consequently, your select statement should be ok. This most likely means that the index "menu_name" can't be found on the $page record.
Check to make sure that "menu_name" is indeed a column of the pages table.
To test what valid columns the $page record has you can use the following inside the while $page loop:
var_dump($page);
If the subject id is an integer you do not need single quotes in the where clause. However, if the subject_id contains any non-integer characters, your select statement would need to be:
$page_set = mysql_query("SELECT * FROM pages WHERE subject_id = '{$subject["id"]}'", $connection);