How to display group data based on end date? - javascript

I have a table like below:
How can i display the data based on task end date with new table. Meaning that, the full <div tag`` will repeat for each ending date and display the records on columns. For example-
**Staff 1**
Date: 2020-11-14
Date: 2020-11-27
**Staff 2**
Date: 2020-11-14
Thanking in anticipation.
<div>
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>Task Name</th>
<th>Remarks</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
<?php
$sql = "SELECT * FROM dl_fullremarks ";
$result = mysqli_query($conn, $sql);
foreach ($result as $row) {?>
<tr>
<td><?php echo $row['staff_id']; ?></td>
<td><?php echo $row['task_name']; ?></td>
<td><?php echo $row['task_remarks']; ?></td>
<td><?php echo $row['task_startdate']; ?></td>
<td><?php echo $row['task_enddate']; ?></td>
</tr>
<?php
}
?>
</table>
</div>

You can fetch your data first with SQL and then organize it with a PHP associative array :
$data = [];
foreach ($result as $row) {
// Check if the current end date is part of the array. If not, add it
if (!isset($data[$row['task_enddate']]) {
$data[$row['task_enddate']] = [];
}
// Add the row to the assigned end date
$data[$row['task_enddate']][] = $row;
}
$data nows contains the following structure :
[
'2020-11-14' => [
['staff_id' => 1, 'task_name' => 'name', // ...],
['staff_id' => 2, 'task_name' => 'other name', // ...],
],
'2020-12-16' => [
['staff_id' => 3, 'task_name' => 'name', // ...],
],
]
You can now loop through it to display your template :) !
foreach ($data as $date => $rows) {
echo '<div>';
echo "<div>$date</div>";
echo '<div class="row">';
foreach ($rows as $row) {
// Display your row data here
}
echo '</div></div>';
}

Group result set by task_endtime:
SELECT * FROM dl_fullremarks
WHERE staff_id = '1'
ORDER BY task_endtime
When task_endtime changed from last saved then print header. All other rows are printed as in your example.
$prev_endtime = null
foreach ($result in $rows) {
if (date('Y-m-d', $row['taks_endtime']) != $prev_endtime) {
echo '<div class="header">date formatted here</div>';
$prev_endtime = date('Y-m-d', $row['task_endtime']);
}
echo '<div class="row">row cells gere</div>';
}

Related

Call php function from Javascript inside php file

I have a php file that shows all the user details in table form. On click of edit, I am want to set something from DB to local storage using javascript.
So to show a table of users I am doing the following:
<table cellspacing="0">
<tr>
<th>ID</th>
<th>Name</th>
<th>View</th>
<th>Edit</th>
</tr>
<?php
$count=1;
$sel_query="Select * from user_details ORDER BY id desc;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td align="center"><?php echo $count; ?>
<td align="center"><?php echo $row["docname"]; ?>
<td align="center">View</td>
<td align="center">Edit</td>
</tr>
<?php $count++; } ?>
</table>
The above shows the records in the table perfectly.
Now when edit is clicked, I call a javascript function. (This is called before I click on edit? I am not sure why?)
<script type="text/javascript">
function handleLinkClick (e) {
e.preventDefault ();
var id = e.target.href.split ("?").pop ();
var key = <?php echo add(id);?>
console.log(key);
localStorage.setItem ("myKey", key);
//window.location.href = e.target.href;
}
</script>
Now from javascript function, I am trying to call a PHP function a variable is sent from javascript to PHP function to fetch corresponding records details and return that data to javascript, below is the PHP function:
function add($id){
$sel_query="select * from user_details where id=$id";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result))
{
$key = $row["rawText"];
echo $key;
}
return $key;
}
?>
I don't see any results. I am not sure why I am not getting any results? Can some give me the right syntax or correct me?
Thanks!

How to solve Notice: Trying to get property of non-object (Caused by table altering)

I need to ask this question and I know this might get mark as duplicate since so many people already ask the similar questions but I have read through them and find no answers or similarities to the problem that I'm facing.
Trying to get property of non-object
Okay, right now, I have a table that will show the list of a user for admin to add, edit or delete the user. My problem right now is, the table can only display the users list and when I add the edit and delete part, the notice pops up.
This is my code before alteration of edit and delete;
<?php
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = ''; // Password
$db_name = 'register'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = 'SELECT *
FROM users';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<table class="data-table">
<caption class="title">List of Users </caption>
<thead>
<tr>
<th>USERNAME</th>
<th>PASSWORD</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td>'.$row['username'].'</td>
<td>'.$row['password'].'</td>
</tr>';
}?>
</tbody>
</table>
and here is my code after the alteration
<?php
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = ''; // Password
$db_name = 'register'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = 'SELECT *
FROM users';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<table class="data-table">
<caption class="title">List of Users </caption>
<thead>
<tr>
<th>USERNAME</th>
<th>PASSWORD</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo "<tr>";
echo "<td>" . $row->username . "</td>";
echo "<td>" . $row->password . "</td>";
echo "<td><a href='records.php?id=" . $row->id . "'>Edit</a></td>";
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
echo "</tr>";
}?>
</tbody>
</table>
</div>
</body>
Where did I do wrong and how can I solve my problem?
Every suggestion and hints are greatly appreciated and please don't mark my question since I believe that my question is totally different from the others.

Ajax request data could not show into the input field

I have created a loop which contains a dropdown list and input field.
What I need is:
When I select a value from dropdown list of Fruit Genres, the Unit Price field will display value come from database. I did all of these, but could not display value to the Unit Price field.
Here is my code:
View page:
<div class="table-responsive">
<table class="table table-hover" id="item-tbl">
<thead>
<tr>
<th class="text-center">Fruit Type</th>
<th class="text-center">Fruit Genres</th>
<th class="text-center">Qty</th>
<th class="text-center">Unit Price</th>
<th class="text-center">Sub Total</th>
</tr>
</thead>
<tbody>
<?php for($i=1; $i<=3; $i++){ ?>
<tr style="">
<td><?php echo $this->Form->input('fruit_type_id', ['options'=>$fruit_types, 'empty'=>'Select Fruit Type', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_type_id]']); ?></td>
<td><?php echo $this->Form->input('fruit_genre_id', ['options'=>$fruit_genres, 'empty'=>'Select Fruit Genre', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_genre_id]', 'class'=>'fruit_genre']); ?></td>
<td><?php echo $this->Form->input('quantity', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][quantity]', 'class'=>'quantity', 'id'=>'quantity_'.$i]); ?></td>
<td><?php echo $this->Form->input('price', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'price', 'id'=>'price_'.$i]); ?></td>
<td><?php echo $this->Form->input('sub_total', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'sub_total']); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var priceId = $(this).closest('tr').find('.price').attr('id');
// alert(priceId);
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// $(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
$(priceId).val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});
OrdersController.php
public function getFruitById($id){
$this->viewBuilder()->layout('ajax');
$this->loadModel('FruitGenres');
$item = $this->FruitGenres->get($id);
if (!empty($item)) {
$response['code'] = 200;
$response['message'] = 'DATA_FOUND';
$response['data'] = $item;
}else{
$response['code'] = 404;
$response['message'] = 'DATA_NOT_FOUND';
$response['data'] = array();
}
$this->set('response', $response);
$this->set('_serialize', ['response']);
}
I have got the expected data to the javascript console. but could not pass the data to the input field.
I have tried:
$(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
instead of
$(priceId).val(returnData.response.data.unit_price);
into the ajax success function, but it did not worked.
if I add a static id like the following:
$('#price_1').val(returnData.response.data.unit_price);
then it works.
Can anyone please help me? I am stuck on it.
I am using cakephp 3 for my project.
priceId is a value like price_1 without #. To make it a selector by id - prepend it with #:
$("#" + priceId).val(returnData.response.data.unit_price);
You can even simplify your code:
// you get id of the found element so as to find this element again
// you can store founded element instead of it's id
var priceDiv = $(this).closest('tr').find('.price');
// in success callback:
priceDiv.val(returnData.response.data.unit_price);
You can select the element directly instead of getting its ID and select with another jQuery call.
Another thing to note - this in the submit callback refer to the callback function itself, not the element.
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var $price = $(this).closest('tr').find('input.price'); // Get the element
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// Use $price directly as a jQuery object
$price.val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});

Codeigniter: Using button click to view more data from database

Ideally, In my database table, I have username, name, location, email.
Now I have a table in my view.php where it returns value from the database.
Table header consists of name, username, and more info where name and username comes directly from the database while more info will have a button for each row. When the button is clicked, it should display location and email in a pop up.
Question: How can I retrieve location and email of a user when the button is clicked specifically?
Example:
user1, joe doe, [button] -> user1 location, user1#email.com
user2, jay doe, [button] -> user2 location, user2#email.com
Codes: p.s. code includes pagination.
controller.php
function pagination() {
$config = array();
$config['base_url'] = base_url() . "controller/pagination";
$total_row = $this->model->record_count();
$config["total_rows"] = $total_row;
$config["per_page"] = 8;
$config['uri_segment'] = 3;
/* $config['use_page_numbers'] = TRUE; */
$config['num_links'] = $total_row;
$config['cur_tag_open'] = ' <a class="current">';
$config['cur_tag_close'] = '</a>';
$config['next_link'] = '<span aria-hidden="true">»</span>';
$config['prev_link'] = '<span aria-hidden="true">«</span>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->model->fetch_data($config["per_page"], $page);
$str_links = $this->pagination->create_links();
$data["links"] = explode(' ', $str_links);
// View data according to array.
$this->load->view("view-employees", $data);
}
model.php
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
view.php
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data->username; ?></td>
<td><?php echo $data->name; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data->location;
echo $data->email;
?>
</button>
</td>
</tr>
You could write a Codeigniter-controller which will return email and location
Then you write Javascript-functions which will call this controller to retrieve the data asJSON-Data
Both, writing a controller which returns JSON and an example how to call this controller from JS can be found here:
Code Igniter - How to return Json response from controller
Try like this..
MODEL:
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
return false;
}
View:
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data['username']; ?></td>
<td><?php echo $data['name']; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data['location'];
echo $data['email'];
?>
</button>
</td>
<?php } ?>
</tr>

How do I email an html table containing mysql result data with a button in php?

Sorry if this is a poor description, I am relatively new to this.
I am developing a web tool which displays the results of mysql data filtered by a date range in an html table. I have an input and button which allows the user to input an email address to send the table data to. The problem is I am having trouble passing the html table data correctly to my php page to be emailed.
I've tried various methods with AJAX and Javascript, but nothing is working. At one point I was able to pass the table data, but not the inputted email (or vice versa); never both simultaneously. I need to be able to pass both the email that has been inputted as well as the data in the html table preferably reserving the table format as well for a cleaner look). Any help and/or insight is greatly appreciated. Apologies if this code is improper and/or wrong.
Relevant PHP:
<!-- download2csv button -->
<div>
<form action="getCSV.php" method="post">
<input type="hidden" name="csv_text" id="csv_text_computers">
<button class="btn btn-app btn-primary btn-xs no-radius" type="submit" onclick="getCSVDataComputers()">
<i class="icon-save"></i></button>
</form>
<!-- email button -->
<form action="mailto.php" method="post">
Email: <input type="text" name="einame" id="eiid" placeholder="example#example.com">
<button class="btn btn-app btn-info btn-xs no-radius" type="submit" name="ebname" id="ebid" onclick="mailer()">
<i class="icon-envelope"></i></button>
</form>
</div>
</div>
<!-- data table header -->
<div class="table-responsive">
<table id="table-computers1" name="table-computers" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Item Name</th>
<th>RFID Number</th>
<th>Link</th>
<th>Delivery Date</th>
</tr>
</thead>
<tbody>
<?php
foreach ($infocoms as $infocom)
{
//variables for glpi url
$itemtype = $infocom['itemtype'];
$items_id = $infocom['items_id'];
$url = "https://null.null.com/front/" . $itemtype. ".form.php?id=" . $items_id;
?>
<tr>
<?php
// database connection
$conn = mysqli_connect('null', 'null', 'null');
mysqli_select_db($conn, 'glpi');
if ($infocom['itemtype'] == "peripheral") {
$query = "SELECT glpi_peripherals.name AS devicename, TRIM(LEADING '0' FROM glpi_peripherals.otherserial) AS otherserial FROM glpi_peripherals INNER JOIN glpi_infocoms ON glpi_peripherals.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'peripheral'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$devices = $result->fetch_assoc();
echo "<td>$devices[devicename]</td>";
echo "<td><center>$devices[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "computer") {
$query = "SELECT glpi_computers.name AS compname, TRIM(LEADING '0' FROM glpi_computers.otherserial) AS otherserial FROM glpi_computers INNER JOIN glpi_infocoms ON glpi_computers.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'computer'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$computers = $result->fetch_assoc();
echo "<td>$computers[compname]</td>";
echo "<td><center>$computers[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "monitor") {
$query = "SELECT glpi_monitors.name AS viewname, TRIM(LEADING '0' FROM glpi_monitors.otherserial) AS otherserial FROM glpi_monitors INNER JOIN glpi_infocoms ON glpi_monitors.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'monitor'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$monitors = $result->fetch_assoc();
echo "<td>$monitors[viewname]</td>";
echo "<td><center>$monitors[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "networkequipment") {
$query = "SELECT glpi_networkequipments.name AS netname, TRIM(LEADING '0' FROM glpi_networkequipments.otherserial) AS otherserial FROM glpi_networkequipments INNER JOIN glpi_infocoms ON glpi_networkequipments.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'networkequipment'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$networks = $result->fetch_assoc();
echo "<td>$networks[netname]</td>";
echo "<td><center>$networks[otherserial]</center></td>";
} elseif ($infocom['itemtype'] == "printer") {
$query = "SELECT glpi_printers.name AS printname, TRIM(LEADING '0' FROM glpi_printers.otherserial) AS otherserial FROM glpi_printers INNER JOIN glpi_infocoms ON glpi_printers.id = glpi_infocoms.items_id WHERE glpi_infocoms.items_id = $infocom[items_id] AND glpi_infocoms.itemtype = 'networkequipment'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$printers = $result->fetch_assoc();
echo "<td>$printers[printname]</td>";
echo "<td><center>$printers[otherserial]</center></td>";
} else {
// error handling for null entries
echo "1 or more items were not found";
}
// end data loop and close mysql connection
mysqli_close($conn);
?>
<td><a target=_blank href=$url><?php echo $url; ?></a></td>
<td><center><?php echo $infocom['ddate']; ?></center></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</form>
</div>
<?php
} else {
echo "<center><p style='font-size:125%;'>Please select a date range to submit.</p></center>";
}
error_log("\n");
?>
Relevant Javascript:
<script type="text/javascript">
jQuery(function($) {
var oTable1 = $('#table-computers').dataTable( {
"aLengthMenu": [[10, 25, 100, -1], [10, 25, 100, "All"]],
"iDisplayLength": -1,
"aoColumns": [
{ "bSortable": true },
null, null,null,
] } );
})
function getCSVDataComputers(){
var csv_value=$('#table-computers').table2CSV({delivery:'value'});
$("#csv_text_computers").val(csv_value);
}
</script>
<script type="text/javascript">
function mailer()
{
var tableContent=document.getElementById("table-computers").innerHTML;
alert(tableContent); // This works, but data does not echo in mailto.php
$.post('mailto.php',{content:tableContent},function(data) {
});
}
</script>
Mailto PHP page:
<?php
$mailto = $_POST['einame'];
$table = $_POST['tableContent'];
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: Test <test#example.com>' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
if (isset($mailto)) {
mail($mailto,"GLPI Notifications",$table,$headers);
echo "Mail sent successfully to $mailto." . "\r\n";
} else {
echo "Mail was not sent." . "\r\n";
}
?>
<br>
Home Page
<br>
<?php
echo $table; // Displays nothing
error_log("\n");
?>
finally figured it out. updated code:
function mailer() {
var tableContent=document.getElementById("table-computers").innerHTML;
// alert(tableContent); confirmation
$.post("mailto.php",{ "content": $("#bmailto").val(tableContent) },function(data) {
});
}

Categories