I am new to the programming. I have created a web application (MVC4) which displays the table from SQL like:
----------------------------------
Wavelength | Values | Date | Time
----------------------------------
228 | 0 |10 Oct| 9:00
229 | 0.5 |10 Oct| 9:00
. . . .
. . . .
. . . .
228 | 0.1 |11 Oct| 8:00
229 | 0.3 |11 Oct| 8:00
. . . .
. . . .
. . . .
228 | 0.6 |11 Oct| 10:00
229 | 0.2 |11 Oct| 10:00
----------------------------------
How can I display it like:
-------------------------------------
| 10 Oct | 11 Oct
--------------------------
Wavelength | 09:00 | 08:00 | 10:00
--------------------------
| Values | Values | Values
-------------------------------------
228 | 0 | 0.1 | 0.6
229 | 0.5 | 0.3 | 0.2
------------------------------------
Should I go for Dynamic SQL Pivot or it can achieved by some client side technique. suggestions please.
I,m sorry if you found this question as not specific.
Thank you :)
This way you can do dynamic pivoting, this code was tested in sql server,
declare #allval varchar(500)
declare #sql varchar(500)
create table #table (wavelength varchar(50), value decimal(2,2), [date] varchar(10), [time] varchar(10))
insert into #table values
(228 ,0,'10 oct','9:00'),
(229 ,0.5,'10 oct','9:00'),
(228 ,0.1,'11 oct','8:00'),
(229 ,0.3,'11 oct','8:00'),
(228 ,0.6,'11 oct','10:00'),
(229 ,0.2,'11 oct','10:00')
select #allval = (select Stuff((SELECT distinct ', ' + concat('[',date,' ',time,']')
FROM #table l
FOR XML PATH('')),1,1,'') )
select #sql = 'select * from
(select concat(date,'' '',time) as datetime,wavelength,value from #table )j
pivot (max(value)
for [datetime] in(' + #allval+ '))p'
exec(#sql)
drop table #table
Related
I am trying to compare two strings using ajax and php. I am based on this code https://github.com/webhostguru/dynamic-drop-down. I change the code on the ajaxdata.php file and it looks like this
<?php
include_once 'config.php';
if (isset($_POST['country_id'])) {
$query = "SELECT * FROM state where state_name=".$_POST['country_name'];
$result = $db->query($query);
if ($result->num_rows > 0 ) {
echo '<option value="">Select State</option>';
while ($row = $result->fetch_assoc()) {
echo '<option value='.$row['id'].'>'.$row['state_name'].'</option>';
}
}else{
echo '<option>No State Found!</option>';
}
The rest of the code is the same. I change also some of sql tables and i have a state named India to compare the strings with country (India also) but it doesn't work. Any ideas?
Thank you in advance!!!
To use a prepared statement you can try like this:
<?php
if( isset(
$_POST['country_id'],
$_POST['country_name']
)) {
$output='<option selected hidden disabled>Please Select State';
require 'config.php';
$query = 'select `id`, `state_name` from `state` where `state_name`=?';
$stmt=$db->prepare( $query );
$stmt->bind_param('s', $_POST['country_name'] );
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->bind_result( $id, $name );
if( $rows > 0 ){
while( $stmt->fetch() ) $output .= sprintf('<option value="%s">%s',$id,$name);
}else{
$output='<option selected hidden disabled>No state found';
}
exit( $output );
}
?>
Based upon the database cited but modified slightly for table names:
mysql> select * from tbl_country;
+----+--------------+---------------------+
| id | country_name | time_stamp |
+----+--------------+---------------------+
| 1 | India | 2019-12-05 16:29:16 |
| 2 | USA | 2019-12-05 16:29:16 |
| 3 | Australia | 2019-12-05 16:29:44 |
| 4 | England | 2019-12-05 16:29:44 |
+----+--------------+---------------------+
mysql> select * from tbl_state;
+----+-----------------+------+---------------------+
| id | state_name | c_id | time_stamp |
+----+-----------------+------+---------------------+
| 1 | Delhi | 1 | 2019-12-05 16:30:15 |
| 2 | Maharashtra | 1 | 2019-12-05 16:30:15 |
| 5 | South Australia | 3 | 2019-12-05 17:02:22 |
| 6 | West Australia | 3 | 2019-12-05 17:02:22 |
+----+-----------------+------+---------------------+
mysql> select * from tbl_city;
+----+------------+------+---------------------+
| id | city_name | s_id | time_stamp |
+----+------------+------+---------------------+
| 1 | East Delhi | 1 | 2019-12-05 16:31:42 |
| 2 | West Delhi | 1 | 2019-12-05 16:31:42 |
| 3 | Mumbai | 2 | 2019-12-05 16:32:49 |
| 4 | Pune | 2 | 2019-12-05 16:32:49 |
| 5 | Adelaide | 5 | 2019-12-05 17:03:01 |
+----+------------+------+---------------------+
And a marginally different piece of PHP
<?php
#hardcode POST values for testing...
$_POST['country_id']=1;
$_POST['country_name']='India';
if( isset(
$_POST['country_id'],
$_POST['country_name']
)) {
$output='<option selected hidden disabled>Please Select State';
#require 'config.php';
# pertinent to my system
require '../../dbo/db-conn-details.php';
require '../../dbo/mysqli-conn.php';
# joining all tables
$query='select distinct ct.`id`,s.`state_name` from `tbl_country` ct
join `tbl_state` s on s.`c_id`=ct.`id`
join `tbl_city` c on c.`s_id`=s.`id`
where ct.`country_name`=?';
$stmt=$db->prepare( $query );
$stmt->bind_param('s', $_POST['country_name'] );
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->bind_result( $id, $name );
if( $rows > 0 ){
while( $stmt->fetch() ) $output .= sprintf('<option value="%s">%s',$id,$name);
}else{
$output='<option selected hidden disabled>No state found';
}
exit( sprintf('<select>%s</select>',$output ) );
}
?>
Results in generated HTML like this:
<select>
<option selected="" hidden="" disabled="">Please Select State</option>
<option value="1">Delhi</option>
<option value="1">Maharashtra</option>
</select>
I want to sort my table columns by angular-dataTables. However, it sort the productCurrency because of 'ng-if' first then only to sort the productType. Any suitable function of dataTable can sort the table correctly? Check my output:
My Output:
|Product |
|CHN Product1|
|USD Product1|
|ABC |
|BBC |
|BBC |
|ZBC |
Expected Output:
|Product |
|ABC |
|BBC |
|BBC |
|CHN Product1|
|USD Product1|
|ZBC |
You can see it was supposed to sort product by alphabet, but it sort by currency 1st then the product type.
(Edited) PS: USD & CHN is productCurrency; Product1, ABC, BBC, ZBC is productType.
Here are my code:
ViewUserType.html
<td>
<span ng-if="ctrl.productType='ABC'" translate="ctrl.productCurrency.translateKey"> {{ctrl.productCurrency}}</span>
<span translate="ctrl.product.type.translateKey">{{ctrl.productType}}</span>
</td>
Controller.js
ctrl.dtOptions = DTOptionsBuilder.newOptions().withOption('aaSorting', [[2, 'desc'], [1, 'desc']]).withOption('pageLength', 25);
Let's assume I have a MySQL structure like this...
+--------------+--------------------+-------------------+
| tdate | tuser | tvalue |
+--------------+--------------------+-------------------+
| 11:16:48 | John | 10 |
+--------------+--------------------+-------------------+
| 11:16:38 | John | 40 |
+--------------+--------------------+-------------------+
| 11:16:28 | Lisa | 50 |
+--------------+--------------------+-------------------+
| 10:16:48 | Lisa | 20 |
+--------------+--------------------+-------------------+
and a php query like this:
<?php
$username = 'test';
$sql=mysqli_query($db,"SELECT * FROM t ORDER BY tid DESC LIMIT 20");
while($row=mysqli_fetch_array($sql))
{
$tuser= $row['tuser'];
$tvalue= $row['tvalue'];
$tdate= $row['tdate'];
?>
<div id="<?php echo $tvalue; ?>" class="message_box">
<?php echo $tdate; ?> -
<?php echo $tvalue; ?> -
<?php echo $tuser; ?>
</div>
<?php
}
?>
This currently lists the mysql table by each row like this:
2016-02-22 11:16:48 - 10 - John
2016-02-22 11:16:38 - 40 - John
2016-02-22 11:16:28 - 50 - Lisa
2016-02-22 10:16:48 - 20 - Lisa
I would like to see it like this:
2016-02-22 11:16:48 - 50 - John
2016-02-22 11:16:28 - 50 - Lisa
2016-02-22 10:16:48 - 20 - Lisa
Meaning that loop would have to sum up values in cases where the new row was created within 60 seconds (for the same user).. Lisa has two rows, but since there is one hour timestamp difference it would have to be listed as usual... It would need it to update automaticaly, meaning that it would show value of 40 for John initially, but after 10 seconds when the new row would be added it would have to update to 50 accordingly. There is also the issue of MYSQL QUERY LIMIT of 20 which could break up rows that were inserted within 60 seconds and give false total value calculation.. I know it's a hard one, but does anyone has a simple solution for this?
Thanks to Asur I currently have this:
SELECT ROUND(UNIX_TIMESTAMP(tdate) DIV 60) AS time,tuser,SUM(tvalue)
FROM t
GROUP BY EXTRACT(DAY_HOUR FROM tdate),tuser
ORDER BY tid DESC
LIMIT 20;
but the problem is that if the last database row is JOHN, he will not be listed out last if there is already one John row above that in the same hour..
IF I HAVE:
JOHN 10
GEORGE 10
GEORGE 10
JOHN 10
It will list:
JOHN 20
GEORGE 20
And it should be the other way arround, where the last row counts:
GEORGE 20
JOHN 20
I would recommend you to do it directly in the sql query as follows:
SELECT ROUND(UNIX_TIMESTAMP(tdate) DIV 60) AS time,tuser,SUM(tvalue)
FROM t
GROUP BY time,tuser
ORDER BY tid DESC
LIMIT 20;
This is long way better in terms of optimization and spent time.
replace this query:
SELECT * FROM t ORDER BY tid DESC LIMIT 20
with this:
SELECT tdate , sum(tvalue), tuser FROM t
group by tuser, DATE_FORMAT(tdate , '%Y-%m-%d %h:%i')
ORDER BY tid DESC LIMIT 20
Ok so here are the tables I have:
departments associates
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
| dep_id | dep_name | date_added | | asso_id | asso_name | dep_id | date_added |
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
| 1 | Pick a Department| Date | | 1 | A Associate | 2 | Date |
| 2 | Department A | Date | | 2 | B Associate | 3 | Date |
| 3 | Department B | Date | | 3 | C Associate | 4 | Date |
| 4 | Department C | Date | | 4 | D Associate | 5 | Date |
| 5 | Department D | Date | | 5 | A Associate 2 | 2 | Date |
+--------+------------------+--------------+ +---------+------------------+-----------+------------+
key_list key_log
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
| key_id | key_name | date_added | | id | key_assigned | key_status | assigned_to | assigned_by |
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
| 1 | Key 1 | Date | | 1 | Key 1 | 0 | A Associate | logged in name |
| 2 | Key 2 | Date | | 2 | Key 4 | 0 | B Associate | logged in name |
| 3 | Key 3 | Date | | | | | | |
| 4 | Key 4 | Date | | | | | | |
| 5 | Key 5 | Date | | | | | | |
+--------+------------+--------------+ +------+--------------+------------+-------------+----------------+
So I'm trying to create a key log where I can store key names and associate names, and if the key was logged out or in. My first issue came when trying to link dropdown menus for departments and associates. I learned that you don't put comas for joins and someone suggested to just go ahead and use multiple querys.
So after some research I went about it this way:
<?php
$dbhost_name = "localhost";
$database = "db_name";
$username = "user_name";
$password = "password";
try {
$dbo = new PDO('mysql:host='.$dbhost_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<script>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='dd.php?cat=' + val ;
}
</script>
</head>
<body>
<?Php
#$cat=$_GET['cat']; // Use this line or below line if register_global is off
if(strlen($cat) > 0 and !is_numeric($cat)){ // to check if $cat is numeric data or not.
echo "Data Error";
exit;
}
$quer3="SELECT DISTINCT key_name, key_id FROM key_iv order by key_name";
$quer2="SELECT DISTINCT category,cat_id FROM category order by category";
if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT subcategory FROM subcategory where cat_id=$cat order by subcategory";
}else{$quer="SELECT DISTINCT subcategory FROM subcategory order by subcategory"; }
echo "<form method=post name=f1 action='dd-check.php'>";
// Starting of first drop down
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
foreach ($dbo->query($quer2) as $noticia2) {
if($noticia2['cat_id']==#$cat){echo "<option selected value='$noticia2[cat_id]'>$noticia2[category]</option>"."<BR>";}
else{echo "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";}
}
echo "</select>";
// This will end the first drop down list
// Starting of second drop downlist
echo "<select name='subcat'><option value=''>Select one</option>";
foreach ($dbo->query($quer) as $noticia) {
echo "<option value='$noticia[subcategory]'>$noticia[subcategory]</option>";
}
echo "</select>";
// This will end the second drop down list
echo "<input type=submit value=Submit>";
echo "</form>";
?>
</body>
</html>
My problem with this is that when you select a key, and after select a department, the key originally selected gets reset and you have to go back and select the key again. You might say o well just place the keys drop down at the end. Well my intention is later to be able to select a key and with ajax or php check if the key status of that key is 0 (logged out) or 1 (logged back in), if it's on status 0, automatically select the radio button for status 1, and vise versa.
After this I did more research and found this Populate another select dropdown from database based on dropdown selection and so decided to go with this approach:
<?php
$db = new mysqli('localhost', 'carlos', 'Security5', 'testing');
$query = "SELECT dep_id, dep_name FROM department";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("id" => $row['dep_id'], "val" => $row['dep_name']);
}
$query = "SELECT ass_id, dep_id, ass_name FROM associates";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['dep_id']][] = array("id" => $row['ass_id'], "val" => $row['ass_name']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<!docytpe html>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
</head>
<body onload='loadCategories()'>
<?php
$quer3="SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
</body>
</html>
The problem with this is again when I place the first drop down before the other two, the other two don't work, and in this case completely disappear. When I place it after the two drop downs, everything works. I know, why am I not placing it after to fix it. Well like I said before, I need this to work for specifically adding other functionality later. Than and I refuse to accept that this can't be done. Can anyone tell me why this is not working for either method, and for that matter which is the better method.
I think the problem with your second attempt is you get key_name and key_id from your query, but where you write out the values in the options you refer to key_name and id (not key_id):
<?php
$quer3="SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
echo "<select name=key_names><option value=''>Select Key</option>"; // list box select command
foreach ($dbo->query($quer3) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[key_name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
So, fixing that up (and the lack of quotes around names, and lack of escaping of data onto HTML):
<?php
$querykeys = "SELECT DISTINCT key_name, key_id FROM key_list order by key_name";
printf("<select name='key_names'>\n");
printf("<option value=''>Select Key</option>\n");
foreach ($dbo->query($querykeys) as $row) {
printf("<option value='%s'>%s</option>",
htmlentities($row['key_id'], ENT_QUOTES),
htmlentities($row['key_name'], ENT_QUOTES)
);
}
echo "</select>\n";
?>
There is a rather challenging task to implement, which broke my mind completely. Maybe someone will advise how to generate the algorithm based on the following description.
Objective
I have a single container with blocks of static width say 150px. The width of the container for desktop devices is say 600px and for mobile devices is 450px. This means that in the desktop version I have 4 blocks in a row and in the mobile version there are 3 blocks in a row. To complete all space left in a row (if any) I need to add placeholders which look like other blocks but with no content and of different colour. The number of added placeholders should always be the same but some should be hidden in the desktop version and some should be hidden in the mobile version. I need to use CSS for hiding and displaying the placeholders on different screens and JavaScript for adding placeholders on page load.
Examples
Consider the following markup for 5 blocks with content and 3 placeholders:
<section>
<article>Article 1</article>
<article>Article 2</article>
<article>Article 3</article>
<article>Article 4</article>
<article>Article 5</article>
<span>Placeholder 1</span>
<span class="mobile-hide">Placeholder 2</span>
<span class="mobile-hide">Placeholder 3</span>
</section>
DEMO: http://jsfiddle.net/5qpsj/
Here I have 1 basic placeholder and 2 placeholders that are hidden on mobile screens. However if the number of content blocks is 4, then the combination of placeholders becomes different, displaying only 2 placeholders that must be hidden on desktop screens:
<section>
<article>Article 1</article>
<article>Article 2</article>
<article>Article 3</article>
<article>Article 4</article>
<span class="desktop-hide">Placeholder 1</span>
<span class="desktop-hide">Placeholder 2</span>
</section>
DEMO: http://jsfiddle.net/5qpsj/1/
I have tried different number of content blocks and created the following table of possible combinations:
---------------------------------------------------------------------
| Blocks | Placeholders | <no class> | .mobile-hide | .desktop-hide |
---------------------------------------------------------------------
| 0 | 4 | 3 | 1 | 0 |
| 1 | 3 | 2 | 1 | 0 |
| 2 | 2 | 1 | 1 | 0 |
| 3 | 1 | 0 | 1 | 0 |
| 4 | 2 | 0 | 0 | 2 |
| 5 | 3 | 1 | 2 | 0 |
| 6 | 2 | 0 | 2 | 0 |
| 7 | 3 | 0 | 1 | 2 |
| 8 | 1 | 0 | 0 | 1 |
| 9 | 3 | 0 | 3 | 0 |
| 10 | 2 | 2 | 0 | 0 |
| 11 | 1 | 1 | 0 | 0 |
| 12 | 0 | 0 | 0 | 0 |
| 13 | 3 | 2 | 1 | 0 |
| ... | ... | ... | ... | ... |
---------------------------------------------------------------------
Starting from 13 blocks the combinations remain the same as for 1 block, 2 blocks, etc. Personally I don't see any pattern in these numbers, which stops me from writing appropriate algorithm for adding placeholders and setting the required classes on page load.
Of course I could hard code the values from 0 to 12 number of blocks, or use approach which checks the width of the container on page resize and add/remove required number of placeholders (performs badly!), but my aim is to generate the code, which does all this job once on load, and then rely on CSS only.
So basically, something like that:
for (var i = 0; i < [number_of_placeholders]; i++) {
var placeholder = document.createElement('span');
if ([condition]) {
placeholder.className = 'mobile-hide';
}
if ([condition]) {
placeholder.className = 'desktop-hide';
}
section.appendChild(placeholder);
}
Do you have any ideas?
So, here is my approach. Feel free to replace the jQuery bits with VanillaJS. You could probably get a bit cleverer with the placeholders needed and calculate whether there are some shared among desktop and mobile. I just added them separately and would let CSS take care of that. See my example here http://jsfiddle.net/yThng/ (add more .blocks and run again to see that it works):
function generatePlaceholders(){
var mobileRowCount = 3, // blocks per row on mobile
desktopRowCount = 4, // blocks per row on desktop
// how many blocks are there?
blockCount = $('.block').length,
// how many placeholders on mobile/desktop needed
mobilePlaceholders = 0,
desktopPlaceholders = 0,
// iterator
i;
// use modulo to see if there are rows that are not filled (on mobile)
if( blockCount%mobileRowCount > 0 ){
// if there are, calculate how many placeholders needed
mobilePlaceholders = mobileRowCount - blockCount%mobileRowCount;
}
// same as above, but for desktop
if( blockCount%desktopRowCount > 0 ){
desktopPlaceholders = desktopRowCount - blockCount%desktopRowCount;
}
// append needed desktop placeholders
for( i=0; i < desktopPlaceholders; i++ ){
$('#container').append('<div class="desktop-only-placeholder" />');
}
// append need mobile placeholders
for( i=0; i < mobilePlaceholders; i++ ){
$('#container').append('<div class="mobile-only-placeholder" />');
}
}