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
Related
I have a PHP function that returns a single row from a localhost MySQL table like so:
<?php
//include database connection process
require_once("includes/conn.inc.php");
//prepare statement
$stmt = $conn->prepare("Select * FROM races WHERE raceID = ?");
$id = 1;
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
?>
What I would like to do with this array is output the data from the individual fields in their own HTML <div> or <p> with a heading indicating what they mean in a separate div. I currently user the print_row method that outputs everything in one. All the data I want is there, but I'd like it separated out into name/value paragraphs or divs.
//what I currently have
<?php
print_r($row);
?>
Is there a way to do this?
Thanks in advance,
Mark
I didn't understand the question very well but I think I understand what you need.
Use while to iterate trough each row.
while($row = $resultDesc->fetch_assoc())
{
echo '<p><strong>Description:</strong></p> ';
echo '<p>'. $row['description'] . '</p>';
}
That's not the exact solution but atleast shows you the path.
You can use foreach
<?php foreach ($row as $key => $val): ?>
<p><strong><?php echo $key; ?>:</strong></p>
<p>
<?php
//output relevant attribute
//of query run on page load
echo $val;
?>
</p>
<?php endforeach; ?>
I am having trouble in getting checked values checked in form. I was trying to use the same function as I have used to insert values to print all values in edit form, and which are in other table inserted to mark them checked.
Function to insert values in database table in insert form and it works.
function emarketing_usluge(){
$link = new mysqli("localhost", "xxx", "xxx", "xxx");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT * FROM `jos_ib_emarketing_oprema` order by OpremaId asc ");
while($record = mysqli_fetch_array($sql)) {
echo '<input type="checkbox" name="usluge[]" value="'.$record['OpremaId ']. '">' . $record['OpremaNaziv'] . ' <br/><br/> </input>';
}
}
In this function I get list of all services and place them in checkboxes.
Now I want to edit form, and display all values that are checked by using same function.
First I make query to get values, I am using here pdo but for funcion files I have used mysqli.
Form for editing!
$sql_oprema = "SELECT a.Partner, a.OpremaId, a.Oprema, b.OpremaNaziv
FROM jos_ib_emarketing_stavke_oprema a
join jos_ib_emarketing_oprema b
on OpremaId = b.Oprema
WHERE a.Partner= $id";
$oprema = $conn->query($sql_oprema);
$row = $oprema ->fetch();
<div class="col-xs-6">
<input type="checkbox" id="oprema" onclick="Exposeoprema()">Oprema<br>
<div id="Scrolloprema" style="height:150;width:200px;overflow:auto;border:1px solid blue;display:none">
<?php
while($row = $oprema ->fetch()) {
$data='<input type="checkbox" name="oprema[]" value="'.$row["Oprema"].'"';
if(isset($row['Oprema'])) {//field in the database
$data.=' checked="checked';
}
$data.='">'. $row["OpremaNaziv"] .'</br>';
}
emarketing_oprema($data);
?>
</div>
</div>
I am trying print all service values by using function, but the ones that are checked they need to have check mark. I am getting problem and could not figure it out how to solve it.
Looking back to your SQL query, I don't see an extraction of checked field, you are not selecting it. So there is never going to be a $row['checked'] element of your query.
You should add:
$sql_oprema = "SELECT a.checked, a.Partner, a.OpremaId, a.Oprema, b.OpremaNaziv
FROM jos_ib_emarketing_stavke_oprema a
join jos_ib_emarketing_oprema b
on OpremaId = b.Oprema
WHERE a.Partner= $id";
I am using function to display all values from tables but the ones that are checked in another table to be checked.
I am trying to print all values from one table, print them in checkbox. Then I am using this function to display all values and mark values checked if they are selected in another table.
function emarketing_oprema_checked(){
$id = test_input($_GET['id']);
$link = new mysqli("localhost", "xxx", "xxx", "xxx");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT a.OpremaId, a.OpremaNaziv, b.Oprema, b.Partner
FROM jos_ib_emarketing_oprema a
LEFT JOIN jos_ib_emarketing_stavke_oprema b ON a.OpremaId = b.Oprema where Partner = $id ");
while($record = mysqli_fetch_array($sql)) {
$data='<input type="checkbox" name="oprema[]" value="'.$record["OpremaId"].'"';
if(isset($record['Oprema'])) {//field in the database
$data.=' checked="checked';
}
$data.='">'. $record["OpremaNaziv"] .'</br>';
echo $data;
}
}
As a result I got only checked values, not the ones that are not checked.
Here is my form
<div class="col-xs-6">
<input type="checkbox" id="oprema" onclick="Exposeoprema()">Oprema<br>
<div id="Scrolloprema" style="height:150;width:200px;overflow:auto;border:1px solid blue;display:none">
<?php
emarketing_oprema_checked();
?>
</div>
</div>
The isset($record['Oprema'] will always be true, even if the value of it is null because the field is exists.
You need to check the value of it.
Try:
if ($record['Oprema']) {
$data.=' checked="checked';
}
I am trying to combine two things which are already know how to do, but can't figure out how to combine them. Here is what I want to achieve:
I have a database with locations and events. There are several events in each location. I will be using PHP to query the database and output the code needed to display search results. I want something similar to the below:
<div id="location">
<p>Location1</p>
<div id="event">Event1</div>
<div id="event">Event2</div>
<div id="event">Event3</div>
</div>
<div id="location">
<p>Location2</p>
<div id="event">Event4</div>
<div id="event">Event5</div>
<div id="event">Event6</div>
</div>
I know that I can use select distinct to get the unique value of each location, and know that I can use a normal select statement to get all the events, however how do add all the events inside the location div?
My current PHP looks like this:
$sql ="SELECT location, event from events";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$location = $row['location'];
$event = $row['event'];
echo "<div id="location">
<p>$location</p>
<div id="event">$event</div>
</div>";
}
My current code adds duplicates of the same location with 1 unique event in each. Even if I use select distinct I get the same results. How do I group the events have have the same location?
I think you should write something like:
$sql ="SELECT location, event from events";
$res = mysql_query($sql) or die(mysql_error());
$prevlocation = "";
while($row = mysql_fetch_assoc($res))
{
$location = $row['location'];
$event = $row['event'];
if ( $prevlocation != "" ) // Close previous div if needed
{
echo "</div>";
}
if ( $location != $prevlocation )
{
echo "<div id='location'><p>$location</p>";
$prevlocation = $location;
}
else
{
echo "<div id='event'>$event</div>";
}
}
echo "</div>"; // Close last div
If you have join of two tables, let's assume that your query looks like this:
$sql ="SELECT * FROM events
JOIN locations ON
locations.id=events.loc_id";
And then, within one loop, get events and location arrays:
$res = mysql_query($sql) or die(mysql_error());
$locations = array();
$events= array();
while($row = mysql_fetch_assoc($res))
{
$location = $row['location'];
$event = $row['event'];
$loc_id=$row['loc_id'];
$id=$row['id'];
$events[]=$loc_id.'%'.$event;
if(!in_array($id.'%'.$location,$locations)) { // avoid duplicate entries
$locations[]=$id.'%'.$location;
}
}
And, another loop (+loop inside loop):
for($i=0;$i<count($locations);$i++) {
$location=explode('%',$locations[$i]);
echo "<div class='location'>\n
<p>$location[1]</p>\n";
for($j=0;$j<count($events);$j++) {
$event=explode('%',$events[$j]);
if($event[0]==$locations[$i][0]) {
echo "<div class='event'>".$event[1]."</div>";
}
}
echo "</div>";
}
Not so elegant, but it is working, and produces valid HTML. :)
First, i wanted to make two associative arrays, and to compare keys, but i couldn't, because i couldn't convert ID keys to strings, so i made it with explode (% is separator between key and value).
Code first, explanation after:
$result = mysql_query("INSERT INTO messages (...) VALUES (...)") or die(mysql_error());
$rowID = mysql_insert_id();
if($result) {
$query = mysql_query("
SELECT ... LIMIT 1");
while ($row = mysql_fetch_array($query)) :
$message_id = stripslashes($row["m_id"]);
$message_postedby = stripslashes($row["u_name"]);
$message_text = stripslashes($row["m_text"]);
$date = date('F d, Y \a\t g:iA', strtotime($row["m_date"]));
?>
<div class="wall_message" id="<?= $message_id ?>">
<div class="author"><?= $message_postedby ?></div>
<div class="message"><?= $message_text ?></div>
<div class="date"><?= $date ?></div>
</div>
<?php
endwhile;
} ?>
What I'm doing:
Insert new row into database
Store ID of inserted row in variable $rowID
If insert was successful, query the database to retrieve that row along with any other related information from other tables
Store values from the row in variables
Print the divs containing that info
All of this is being called from a jQuery function, so I'm expecting that all of my HTML will be returned, but nothing is being returned inside the WHILE loop. I can echo text before and after it, and I see it just fine, but nothing inside the loop will print, and I just can't see my mistake. Not getting any errors either.
Thanks.
mysql_fetch_array() doesn't take a query, it takes a resource (result).
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
Also worth nothing that if you are only accessing the associative keys from the result, you should use mysql_fetch_assoc() instead.