Exporting php data in a loop to CSV file - javascript

I have written a code which uses the API of fantasypremierleague.com to extract data. The data is being extracted for 38 gameweeks using a for loop. I print the data using echo to verify that it is correct.
I am having a problem converting the data into CSV files using a script since its in a loop.
After printing information each gameweek i have added a button (in total 38 buttons) which should convert the information of each gameweek to a CSV file.
Currently, all the buttons are printing the information of gameweek 1 even though the script is part of the loop.
ini_set('max_execution_time', 300);
for ($i=1; $i <39 ; $i++) {
$json=file_get_contents("https://fantasy.premierleague.com/drf/entry/1224012/event/".$i."/picks");
$data = json_decode($json, true);
$json1=file_get_contents("https://fantasy.premierleague.com/drf/elements/");
$data1 = json_decode($json1, true);
?>
<table id ="gameweek_history">
<tr>
<th>Average Gameweek Score</th>
<th>Highest Score</th>
<th>Highest Scorer ID</th>
</tr>
</br>
</br>
<td><?PHP echo $data['event']['average_entry_score']; ?></td>
<td><?PHP echo $data['event']['highest_score']; ?></td>
<td><?PHP echo $data['event']['highest_scoring_entry']; ?></td>
</table>
<table id ="gameweek_info">
<tr>
<th>Gameweek</th>
<th>Active Chip</th>
<th>ID</th>
<th>Points</th>
<th>Total Points</th>
<th>Rank</th>
<th>Overall Rank</th>
<th>Gameweek Transfers</th>
<th>Gameweek Transfer Cost</th>
<th>Points on Bench</th>
<th>Bank</th>
</tr>
</br>
</br>
<td><?PHP echo $data['entry_history']['event']; ?></td>
<td><?PHP echo $data['active_chip']; ?></td>
<td><?PHP echo $data['entry_history']['id']; ?></td>
<td><?PHP echo $data['entry_history']['points']; ?></td>
<td><?PHP echo $data['entry_history']['total_points']; ?></td>
<td><?PHP echo $data['entry_history']['rank']; ?></td>
<td><?PHP echo $data['entry_history']['overall_rank']; ?></td>
<td><?PHP echo $data['entry_history']['event_transfers']; ?></td>
<td><?PHP echo $data['entry_history']['event_transfers_cost']; ?></td>
<td><?PHP echo $data['entry_history']['points_on_bench']; ?></td>
<td><?PHP echo $data['entry_history']['bank']; ?></td>
</table>
</br>
</br>
</br>
<script>function doCSV() {
var table1 = document.getElementById("gameweek_history").innerHTML;
var data1 = table1.replace(/<thead>/g, '')
.replace(/<\/thead>/g, '')
.replace(/<tbody>/g, '')
.replace(/<\/tbody>/g, '')
.replace(/<tr>/g, '')
.replace(/<\/tr>/g, '\r\n')
.replace(/<th>/g, '')
.replace(/<\/th>/g, ',')
.replace(/<td>/g, '')
.replace(/<\/td>/g, ',')
.replace(/\t/g, '')
.replace(/\n/g, '');
var table2 = document.getElementById("gameweek_info").innerHTML;
var data2 = table2.replace(/<thead>/g, '')
.replace(/<\/thead>/g, '')
.replace(/<tbody>/g, '')
.replace(/<\/tbody>/g, '')
.replace(/<tr>/g, '')
.replace(/<\/tr>/g, '\r\n')
.replace(/<th>/g, '')
.replace(/<\/th>/g, ',')
.replace(/<td>/g, '')
.replace(/<\/td>/g, ',')
.replace(/\t/g, '')
.replace(/\n/g, '');
var data= data1.concat(data2);
var mylink = document.createElement('a');
mylink.download = "Gameweek.csv";
mylink.href = "data:application/csv," + escape(data);
mylink.click();
}</script>
<button onclick="doCSV()">Export HTML Table To CSV File</button>
<?PHP
}
?>
I expect each button to convert the information of the particular gameweek which the loop is currently on (for e.g. i i=1 then gameweek 1 team should be exported, if i=2 then gameweek2 team should be exported)

You'll need to add unique ids to every table like:
<table id ="gameweek_history<? echo $i; ?>">
Then you'll need to have your javascript refer to the id. Your existing code creates a new script for every table, so to keep doing that, each function will need a unique name that has refers to that table.
<script>function doCSV<? echo $i; ?>() {
var table1 = document.getElementById("gameweek_history<? echo $i; ?>").innerHTML;
It would probably be better to just have one function declared outside the loop with a variable passed into it.
<script>function doCSV(table_number) {
var table1 = document.getElementById("gameweek_history" + table_number).innerHTML;
Then add the table number to each event handler.
<button onclick="doCSV(<? echo $i; ?>)">Export HTML Table To CSV File</button>

Related

Compare and Count Variable Dates?

Using the given statement below I am Receiving the Value of Course end date which is in varchar and coming from MySQL I tried to convert this to date format in $ced & $newformat...all goes fine but when I am trying to compare course end date with the current date it's not comparing... it's only comparing the date and not comparing with year and month
$enddate = $get_students_row['course_end_date'];
$ced = strtotime("$enddate");
$newformat = date('d/m/Y',$ced);
$currentdate = date('d/m/Y');
The function is if $newformat is less than and eqals to current date then field become red
<tr <?php if(($newformat <= $currentdate)): ?> style="color:red;" <?php endif; ?>>
But its not working as excepted its make row red but its only comapring with current date not with month and year....Also i was looking for to get Total count of $newformat.
My Code
<tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
<td><?php echo $students_rollno_class;?></td>
<td><?php echo $students_admission_no;?> </td>
<td><?php echo $students_firstname;?></td>
<td><?php echo $students_contact;?></td>
<td><?php echo $students_reference_no;?></td>
<td><?php echo date('d/m/Y', strtotime($students_date));?></td>
<td><?php echo $newformat;?></td>
</tr><?php
}
?>
You can see the comparison in this national format
$format = "d_m_y";
$date1 = \DateTime::createFromFormat($format, "03_01_12");
$date2 = \DateTime::createFromFormat($format, "31_12_11");
var_dump($date1 > $date2);
Using DateTime::createFromFormat:
$('#timeTable tr td').each(function () {
var dtTd = new Date($(this).html());
var dtNew = new Date();
// 15 minutes is 900000 milliseconds
if (dtTd.getTime() - dtNew.getTime() < 900000 && dtNew < dtTd) {
$(this).parent('tr').addClass('min15');
} else {
if (dtNew > dtTd) {
$(this).parent('tr').addClass('old');
}
}
});
.old {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table id="timeTable">
<tbody>
<tr>
<td>02/07/2015 23:15</td>
</tr>
<tr>
<td>03/09/2015 11:16</td>
</tr>
<tr>
<td>18/02/2020 11:30</td>
</tr>
</tbody>
</table>
$newformat and $currentdate are just simple strings for PHP. And comparing two strings would not give the answer you expect. So it's better to use UNIX time format.
try this:
<tr <?php if(($ced <= time())){
$totalCount++;
echo 'style="color:red;" ';
<?php } ?>>
My <tr> Code
<tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
<td><?php echo $students_rollno_class;?></td>
<td><?php echo $students_admission_no;?> </td>
<td><?php echo $students_firstname;?></td>
<td><?php echo $students_contact;?></td>
<td><?php echo $students_reference_no;?></td>
<td><?php echo date('d/m/Y', strtotime($students_date));?></td>
<td><?php echo $newformat;?></td>
</tr><?php } ?>

outlook mail window with pre populated to sender box not working

errors i get
I have a table that contains details one of this being emails. When i click a link i have outlook mail opening but i want to take the email of that row in the table and put it into the 'to' part of the email. Below i have code for what i am currently doing.
the code below displays the data from my database in a table format
<table class="table table-striped custab">
<thead>
<tr>
<th> </th>
<th>Booking ID</th>
<th> Name</th>
<th>Email</th>
<th>Date</th>
<th>time</th>
<th>No. of guests</th>
<th>Booking Reason</th>
<th>Comments</th>
<th width="110" class="ac">Approved?</th>
</tr>
<thead>
<!-- php function to only select the bookings that have not yet been approved/rejected -->
<?php
include 'config.php';
$select = "SELECT * FROM `booking` WHERE `status`IS NULL ";
$result = $conn->query($select);
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="checkbox" class="checkbox" /></td>
<td><?php echo $row['customer_ID'] ?></td>
<td><?php echo $row['Name'] ?></td>
<td><?php echo $row['Email'] ?></td>
<td><?php echo $row['booking_date'] ?></td>
<td><?php echo $row['booking_time'] ?></td>
<td><?php echo $row['attendee_no'] ?></td>
<td><?php echo $row['booking_reason'] ?></td>
<td><?php echo $row['comments'] ?></td>
<td>
Email this Codesnippet</a>
</td>
</tr>
<?php
}
?>
</table>
The function below gets the pop up to display for outlook mail
<script type="text/javascript"> TriggerOutlook(Email)
{
var $to = 'Email';
var body = "your booking has been approved";
<!-- var body = escape(window.document.title + String.fromCharCode(13)+ window.location.href); --->
var subject = "Your booking request";
window.location.href = "mailto:?body="+body+"&to="+$to+"&subject="+subject;
}
</script>
if i put in an email manually into the var $to = the outlook pop up works however if i try to take the email from the table it doesnt, can anyone help me out to identity where i am going wrong? Thanks!
1 You don't need the PHP $ declaration for variables, thus:
var $to = 'Email';
should be:
var to = 'Email';
more descriptive variables could make future updates easier:
var toAddr = 'Email';
2 Your JavaScript function should be preceded with the function tag
<script type="text/javascript"> TriggerOutlook(Email)
{
changes to:
<script type="text/javascript">
function TriggerOutlook(Email){
3 Use a button rather than link
Replace
Email this Codesnippet</a>
With
<button
onclick="TriggerOutlook(<?php echo $row['Email'];?>)"
value="submit"
>Email this Codesnippet</button>

Delete from database using javascript

I have a page containing a database table with all the rows and columns.
What I am trying to do is to select all the rows I want and then delete them when I click on the button.
This is what I've done so far in the table.php page:
<?php
include "config.php"; //connection to database
incude "home.js";
$funcao="Select * from palavras";
$result=mysqli_query($link, $funcao);
?>
<button id="button_apaga" type="button" onclick="delete()" > DELETE </button>
<?php if($result->num_rows > 0) { ?>
<table class="table">
<tr>
<th>IdPalavra</th>
<th>Palavra</th>
<th>Grau de Dificuldade</th>
<th>Data</th>
<th>Hora</th>
<th>Selecionar</th>
</tr>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<tr role="row">
<td><?php echo $row['idpalavras']; ?></td>
<td><?php echo $row['palavra']; ?></td>
<td><?php echo $row['graudificuldade']; ?></td>
<td><?php echo $row['data']; ?></td>
<td><?php echo $row['hora']; ?></td>
<td><input type="checkbox" name="check" id="checkbox" /></td>
</tr>
<?php } ?>
</table>
<?php }
else{
echo "0 resultados";
} ?>
JavaScript Page (home.js):
function delete(id){
var check = document.getElementById('checkbox');
if(check.checked) {
// sql query
}
My question is how can I do que sql query considering it's in a different page. Can I just open php and put the query inside?
Also how can I receive all the IDs from the selected rows to the function?
Thank you in advance.
One approach would be to use AJAX. For the purpose of condensing the code, I'm going to also incorporate jQuery into this solution. I am also going to change your checkbox to an individual button link for the sake of making this a bit less code. A solution to delete multiple at the same time could work similarly to this, but since you're using AJAX most likely this is going to be easier for your users.
Modify table.php
<?php
include "config.php"; //connection to database
incude "home.js";
$funcao="Select * from palavras";
$result=mysqli_query($link, $funcao);
?>
<?php if($result->num_rows > 0) { ?>
<table class="table">
<tr>
<th>IdPalavra</th>
<th>Palavra</th>
<th>Grau de Dificuldade</th>
<th>Data</th>
<th>Hora</th>
<th>Selecionar</th>
</tr>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<tr role="row" class="palavras_row">
<td><?php echo $row['idpalavras']; ?></td>
<td><?php echo $row['palavra']; ?></td>
<td><?php echo $row['graudificuldade']; ?></td>
<td><?php echo $row['data']; ?></td>
<td><?php echo $row['hora']; ?></td>
<td>Delete</td>
</tr>
<?php } ?>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js?ver=3.3.1"></script>
<script type="text/javascript">
(function($) {
$(document).on('click', '.palavras_row a.palavras_delete', function() {
var _id = $(this).attr('data-id');
var _row = $(this).parent().parent();
$.ajax({
url: 'delete.php',
data: {
idpalavras: _id
},
type: 'POST',
dataType: 'json',
success: function(__resp) {
if (__resp.success) {
_row.remove(); // Deletes the row from the table
}
}
});
});
})(jQuery);
</script>
Create a new file in the same folder as your table.php and name it delete.php
<?php
$idpalavras = filter_input(INPUT_POST, 'idpalavras', FILTER_SANITIZE_NUMBER_INT);
$success = false;
if ($idpalavras) {
include "config.php"; //connection to database
$funcao="delete from palavras where idpalavras = " . $idpalavras;
$result=mysqli_query($link, $funcao);
$success = true;
}
header('Content-Type: application/json');
echo json_encode(array('success' => $success));
The solution above sends a simple command to your PHP backend where the delete query can be run by PHP. You cannot run a mysql command directly from javascript since that is frontend code.
This code is a functional solution, but it is abbreviated; a more complete solution would have more detailed handling of potential errors (either via AJAX or processing your delete query). It should also have some security on your delete.php to make sure unauthorized users aren't able to delete records without the proper permission to do so.

Retrieve data from DataTable plugin using javascript

I am using DataTable plugin for generating data from database using javascript. I am showing that data in table tag like
foreach ($data as $row) {
$total += $row->price;
?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->created_date; ?></td>
<td><?php echo $row->vender; ?></td>
<td><?php echo $row->usertype; ?></td>
<td><?php echo $row->price; ?></td>
<td><?php echo $row->payment_type; ?></td>
<td><?php echo $row->vender_inv; ?></td>
<td><?php echo $row->note; ?></td>
<td><a class="example-image-link" href="<?php echo $row->image; ?>" data-lightbox="example-1"><img style="width:100px !important; height:100px !important;" class="example-image" src="<?php echo $row->image; ?>" alt="image-1" /></a>
</td>
</tr>
<?php
}
Now I want to retrieve individual rows from it, I am trying to do it like this
var table = $('#myTable').DataTable();
table.column(4).eq(0).each( function ( colIdx ) {
console.log( colIdx, table.column( colIdx ).search() );
} );
Look at the rows() API: https://datatables.net/reference/api/rows().every()
table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
var data = this.data();
// ... do something with data(), or this.node(), etc
} );

joined table display without duplicate

I'm trying to get data from database using PHP this the Sql request you'll see that I have 3 tables but in table Milestoneevent I have various values for column libelle so I want to display like this
Id num libelle1 libelle2 libelle3 ..... sql reql request and php
select DISTINCT file.num,file.id as filenumber,file.numlta,milestones.id,milestones.libelle,milestoneevent.idmilestone,milestoneevent.dat,milestoneevent.idfile from file,milestones,milestoneevent where milestoneevent.idfile=FILE.num and milestoneevent.idmilestone=milestones.id
while (row=mysqlfetchassoc(
rs_result)) {
//print_r( $row ); // debug code ?>
<tr>
<td><input type='checkbox' name="approve[]" id="check" value=<?php echo $row['num']?>></td>
<td><?php echo $row['filenumber']; ?></td>
<td><?php echo $row['numlta']; ?></td>
<td><?php echo $row['designation']; ?></td>
<td><?php echo $row['libelle']; ?></td>
<td><?php echo $row['milestonedate']; ?></td>
</tr>
in the picture you see that a row cqn have multiple values for column libelle in different dates
edit
As requested in comments, here is my expected output:
I was forced to add picture here cause in comment discussion can not add it
You can use GROUP_CONCAT, in your query:
select...,GROUP_CONCAT(milestones.libelle SEPARATOR ';'),..FROM....WHERE...GROUP BY milestones.id

Categories

Resources