how to display only 4 result in each page using html & sqlite - javascript

This is me once again as I got some error in previous question in the code. So asking this question once again.
This is code from phonegap app from index html page. I don't know how to get only 4 result from database at each page when a sqlite query processed?
Also I want to add next page button. When clicking on this button next 4 result from database should come. This is code.
function querySuccess(tx, results){
var len = results.rows.length;
var output = '';
for (var i=0; i<len; i++){
output = output + '<li id="' + results.rows.item(i).id + '">' + results.rows.item(i).list_action + '</li>';
}
messageElement.html('<p>There are ' + len + ' items in your list:</p>');
listElement.html('<ul>' + output + '</ul>');
}

Dividng your solution into 3 phases
Phase 1: Using LIMIT Clause you can limit number of rows to be displayed
SELECT expressions FROM tables WHERE conditions ORDER BY expression [ ASC | DESC ] LIMIT number_rows OFFSET offset_value;
For Example:
SELECT employee_id, last_name, first_name
FROM employees
WHERE favorite_website = 'divyashah.in'
ORDER BY employee_id DESC
LIMIT 4;
Phase 2:
As the code provided by you is not efficient to explain but still... Now for your Next button
1) Fetch number of rows from your database table (mysql_num_rows).
2) Store that number in a Variable say 'a'.
3) Divide it(a) with 4 and store it in variable 'b'.
4) Use if > if(b!=0) {display next button} else {no need to display}
Phase 3:
This will fetch your first four rows i.e. from 0 to 4.
<?PHP
$fetch = mysql_query("SELECT * FROM table LIMIT 0, 4")or
die(mysql_error());
?>
Now how can you make the next page show the next 4 records?
you simply have to store the value of the starting row in a variable and pass it in the URL as a GET variable. Also have to check if there was a value already passed or not so we can set a default value in case it wasn't (zero to start from first row):
<?PHP
//check if the starting row variable was passed in URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
?>
Now your query should have this new variable ($startrow) in the LIMIT clause
<?PHP
//this part goes after the checking of the $_GET var
$fetch = mysql_query("SELECT * FROM table LIMIT $startrow, 4")or
die(mysql_error());
?>
Now to see the next 4 records you should have a link which will add 4 to $startrow so you can view the next 4 records
<?PHP
//now this is the link..
echo 'Next';
?>

Related

Is there a way to link spreadsheet information into my HTML file?

I have a CSV file with 3 columns and 223 rows. The columns go from items (A column), description (B column), to type (C column). Each row contains information about each item. I want to insert data from all this spreadsheet into my HTML file. Along with this, I want to save time by not copy and pasting 233 sets of information manually.
Originally the information I needed was on a website, however, I found a suggestion to use a webscraper to get all the information I needed. I did this by using python and now I have all the information in the spreadsheet.
The template I would like to follow is shown (using spreadsheet terms). If I were manually doing this the next line of code would look this but with a B instead of an A (A1->B1)
<p class="item-title">(A1 in spreadsheet)</p>
<p class="w-itemid">ItemID: N/A</p>
<p>• (A2 in spreadsheet)</p>
<ul>
<p>Type: (A3 in spreadsheet</p>
<p>Item Pool: N/A</p>
</ul>
I want the solution to be able to link the information from my spreadsheet into my HTML without spending an immense amount of time copy and pasting 233 items. I do not mind using Javascript, jQuery, or PHP as long as it helps me finish this task.
you can try this solution:
$row = 1;
$columnArray = [];
$resultArray = [];
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
if($row == 1){
$columnArray = $data;
}else{
$tmpArray = [];
for($i=0;$i<count($columnArray);$i++){
$tmpArray[$columnArray[$i]] = $data[$i];
}
$resultArray[] = $tmpArray;
}
$row++;
}
fclose($handle);
}
I'm assuming that the first row of your CSV holds the column names. At the end you will have $resultArray associative array holding all your data.
UPDATE
If your CSV does not contain field names at the first row you can use this code:
$row = 1;
$resultArray = [];
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
$resultArray[] = $data;
$row++;
}
fclose($handle);
}
In this case $resultArray will hold the data as a normal nested array and you can show the info by iterating trough it:
if(count($resultArray)>0){
for($i=0;$i<count($resultArray);$i++){
echo '<p>Item: '.$resultArray[$i][0].'</p>';
echo '<p>Description: '.$resultArray[$i][1].'</p>';
echo '<p>Type: '.$resultArray[$i][2].'</p>';
}
}

concatenate two arrays using javascripts

I have one page on that page pagination are there initially selectable images are coming after selecting 1 or more images user will click on more activities and he want to select more images from that page then he clicks on confirm button all the selected images will go in one array please help me..
check this screen
right now like this coming
localhost/carc_app1/user/modal.php?ids=[{"id":"yoga"},{"id":"aerobics"}][{"id":"net ball"}]
but i want to concatenate both arrays
localhost/carc_app1/user/modal.php?ids=[{"id":"yoga"},{"id":"aerobics"},{"id":"net ball"}]
var item = JSON.parse(localStorage.getItem("test"));
//current page value
var item_json = JSON.stringify(item) ;
var page= <?php echo $json_value; ?>;
var set_image=JSON.stringify(page) ;
var image=set_image.concat(item_json);
alert(image);
// Ok. Let's just parse it once instead of turning it
// into a string and reparsing it 57 times needlessly.
var item = JSON.parse(localStorage.getItem("test"));
// No!!! What is your obsession with stringify???
//current page value
//var item_json = JSON.stringify() ;
var page= <?php echo $json_value; ?>;
// NO. just no.
//var set_image=JSON.stringify(page) ;
var image=page.concat(item);
// You can't alert an array, try console instead
//alert(image);
console.log(image);

Jquery looped array selectors with custom element ID's

Going through the other posts i must either have something wrong with my code or my logic is fundamentally flawed.
So what happens is i have a series of array elements that get called/written, these array elements need to have sub elements modified by java script.
Everything was workign before i needed to add an array i.e i was using a single element selector ID for the functions below and got the correct results. However after adding unique ID's in a loop it doesn't want to change.
So here's what happens, I have a separate div that is hidden. This prints out how many elements are in the array as its a PHP session variable. $Carray is a count function and works correctly.
<div class="Carray"><?php echo $Carray;?></div>
Then as the items are looped they add an array ID
<?php
$arrayID = -1;
foreach($_SESSION['activity'] as $key){
foreach($key as $list){
$arrayID += 1;
?>
<div id="subP_<?php echo $arrayID;?>" class="booking_action">-</div>
<div id="booking_people_<?php echo $arrayID;?>" class="booking_people_number">
<?php echo $list["i_quantity"] ?>
</div>
<div id="addP_<?php echo $arrayID;?>" class="booking_action">+</div>
<?php }} ?>
Then in Javascript i call a loop function that counts through however many $Carray elements there are and then corresponds the correct function actions to the correct div ID's
//get the counted array variable and force as an int
var js_var = parseInt($('.Carray').html(),10);
// loop for however many array elements there are
for (i = 0; i < js_var; i++){
// get the amount of people from a field
var ppl_P = parseInt($('#booking_people_'+i).html(),10);
// subtract 1 person and then change the output to match the new people count
$("#subP_"+i).click(function() {
if(ppl_P >= 2){
ppl_P -= 1;
$('#booking_people_'+i]).html(ppl_P);
}
});
// Add 1 person and then change the output to match the new people count
$("#addP_"+i).click(function() {
ppl_P += 1;
$('#booking_people_'+i).html(ppl_P);
});
}
****************************** EDIT **********************
So based on Jimmi Elofsson answer which works beautifully, i want to expand this to effect elements that are not inside the parent/child selectors. The selector is '.booking_price_inner' which is another div stored elsewhere. I am assuming the line that needs the correct syntax is the marked line.
The '.booking_base_price' is within the parent/child element.
$(".subPerson").click(function() {
// Subtract Person
var subPeopleCount = getCurrentCountByPeopleItem($(this).parent()) - 1;
$(this).parent().children('.booking_people_number').html(subPeopleCount>1 ? subPeopleCount : 1);
//Change price
var totalPriceS = subPeopleCount * getBasePrice($(this).parent());
$(this).parent().children('.booking_price_inner').html(totalPriceS); <-------
});
$(".addPerson").click(function() {
//Add person
var addPeopeCount = getCurrentCountByPeopleItem($(this).parent()) + 1;
$(this).parent().children('.booking_people_number').html(addPeopeCount);
//Change price
var totalPriceA = addPeopleCount * getBasePrice($(this).parent());
$(this).parent().children('.booking_price_inner').html(totalPriceA); <------
});
// get the number of people in the specific array
function getCurrentCountByPeopleItem(peopleItem) {
return parseInt(peopleItem.children('.booking_people_number').html());
}
//get the base price
function getBasePrice(peoplePrice){
return parseInt(peoplePrice.children('.booking_base_price').html());
}
Markup
<div id="<?php echo $arrayID;?>" class="booking_people">
<div class="booking_date_header">People:</div>
<div class="subPerson booking_action">-</div>
<div class="booking_people_number"><?php echo $list["i_quantity"] ?></div>
<div class="addPerson booking_action">+</div>
<div class="booking_base_price"><?php echo $list["i_base_price"] ?></div>
</div>
<div class=spacer></div>
<div class=cost>
<div class=booking_price_inner></div>
</div>
If you don't mind, I did some changes in your code.
you could make your add/substract element use the same click function with the help of some DOM traversing. That way you wouldnt need the CArray to keep track of the buttons.
Javascript:
// subtract 1 person and then change the output to match the new people count
$(".subPerson").click(function() {
var subPeopleCount = getCurrentCountByPeopleItem($(this).parent()) - 1;// Substract by one.
$(this).parent().children('.booking_people_number').html(subPeopleCount>1 ? subPeopleCount : 1);
});
// Add 1 person and then change the output to match the new people count
$(".addPerson").click(function() {
var addPeopeCount = getCurrentCountByPeopleItem($(this).parent()) + 1; // Increase by one.
$(this).parent().children('.booking_people_number').html(addPeopeCount);
});
function getCurrentCountByPeopleItem(peopleItem) {
return parseInt(peopleItem.children('.booking_people_number').html());
}
PHP:
<?php
$arrayID = -1;
foreach($_SESSION['activity'] as $key){
foreach($key as $list){
$arrayID += 1;
?>
<div class="booking_people_item" id="<?php echo $arrayID;?>">
<div class="subPerson booking_action">-</div>
<div class="booking_people_number">
<?php echo $list["i_quantity"] ?>
</div>
<div class="addPerson booking_action">+</div>
</div>
<?php }} ?>
I added a div wrapper around your elements called booking_people_item.
from what I see - you're definig click functions in a loop. Those click functions have a reference to a ppl_P variable. When you define the click, it seems OK. But when the click is triggered, the ppl_P variable is already set to the value from loops last iteration. So, whenever you call that click function, it always has the same result, doesn't it?
The proper way to do it would be to pass this ppl_P variable as a parameter, so you don't have a reference to a variable that was already changed in the other scope. Something like:
function addClickFunction(i, ppl_P){
$("#subP_"+i).click(function() {
if(ppl_P >= 2){
ppl_P -= 1;
$('#booking_people_'+i]).html(ppl_P);
}
});
// Add 1 person and then change the output to match the new people count
$("#addP_"+i).click(function() {
ppl_P += 1;
$('#booking_people_'+i).html(ppl_P);
});
}
And then use this function inside the loop:
var ppl;
for (i = 0; i < js_var; i++){
ppl = parseInt($('#booking_people_'+i).html(),10);
addClickFunction(i, ppl);
}
This hasn't been tested, but I'm pretty sure you'll get the point :)

check if line has already been parsed and inserted into mysql database

I am parsing a whole javascript file (min_day.js) into arrays and then creating INSERT Statements; then executing them with a mysqli_multi_query to get the data into my database
this min_day.js file is updating irregularly (in most cases every 5 min) during the day but it still holds the data from the same day: that means always a new line with data is added on top of the old data
so i am going to configure a cronjob that runs every min to do the parsing and inserting mentioned in the first paragraph but:
now the problem is: how can i only parse and insert the data that has not already been parsed and inserted into the database? how can i check if the data has already been parsed and inserted?
i want to avoid having twice the same data in my database. i guess the solution could be something with using a timestamp... but i'm a beginner and don't know how
// min_day.js file
m[mi++]="24.11.14 08:30:00|196;124;132;55;540;601;45|194;112;123;53;538;606;45|457;350;120;149;570;541;45|452;336;114;146;566;544;46|428;323;107;145;569;541;45|409;325;114;137;572;541;45|38;50;11;407;10|0;0;0;251;14|0;0;0;253;14|11;8;73;0.0;3|16;9;74;0.0;5|13;7;74;0.0;3|16;8;75;0.0;4|18;8;74;0.0;6|0;0;0;310"
m[mi++]="24.11.14 08:25:00|151;106;104;39;539;594;45|147;90;102;37;538;589;45|355;273;96;111;564;540;44|351;259;94;109;566;534;46|348;280;87;110;563;539;45|331;269;97;103;569;536;45|28;38;8;377;10|0;0;0;228;14|0;0;0;239;14|10;8;73;0.0;2|14;8;74;0.0;4|11;7;74;0.0;2|13;8;75;0.0;3|15;8;74;0.0;4|0;0;0;303"
m[mi++]="24.11.14 08:20:00|110;84;85;27;535;586;45|113;74;82;26;533;586;44|283;229;81;83;564;539;44|282;213;76;81;564;536;45|283;223;73;82;566;539;44|266;232;81;76;566;540;45|19;30;0;394;10|0;0;0;230;14|0;0;0;228;14|6;8;73;0.0;1|9;8;74;0.0;3|6;7;74;0.0;1|9;7;75;0.0;2|11;7;74;0.0;3|0;0;0;279"
m[mi++]="24.11.14 08:15:00|94;82;80;18;535;594;44|93;70;76;17;534;599;44|264;215;76;59;558;534;43|262;198;74;58;560;534;45|260;211;66;58;564;537;44|248;208;76;54;560;534;44|17;28;0;394;10|0;0;0;229;14|0;0;0;228;14|6;8;73;0.0;1|9;8;74;0.0;2|5;7;74;0.0;1|8;7;75;0.0;1|10;7;74;0.0;2|0;0;0;281"
m[mi++]="24.11.14 08:10:00|45;47;64;0;556;573;44|62;50;58;9;543;587;43|190;156;59;38;561;528;43|188;148;57;36;557;523;44|189;158;51;37;561;526;44|179;163;61;34;560;521;44|1;11;0;454;10|0;0;0;216;14|0;0;0;213;14|4;8;73;0.0;0|7;8;74;0.0;1|3;7;74;0.0;0|4;7;75;0.0;0|7;7;74;0.0;1|0;0;0;197"
m[mi++]="24.11.14 08:05:00|49;54;55;5;519;551;43|52;44;51;4;517;553;43|151;139;49;22;499;477;42|147;126;47;20;496;466;44|132;120;39;21;530;501;43|130;136;50;19;493;466;43|0;0;0;353;7|0;0;0;206;14|0;0;0;203;14|3;8;73;0.0;0|6;8;74;0.0;0|2;7;74;0.0;0|3;7;75;0.0;0|5;7;74;0.0;0|0;0;0;121"
m[mi++]="24.11.14 08:00:00|36;50;47;1;520;524;43|36;42;48;0;521;531;42|118;112;44;10;470;446;42|116;106;40;9;473;448;44|114;114;37;10;477;452;43|104;120;44;9;471;447;43|0;0;0;0;0|0;0;0;196;14|0;0;0;192;14|3;8;73;0.0;0|6;8;74;0.0;0|1;7;74;0.0;0|2;7;75;0.0;0|5;7;74;0.0;0|0;0;0;118"
m[mi++]="24.11.14 07:56:00|0;12;15;0;641;641;42|0;1;16;0;641;640;42|75;82;33;5;470;446;42|72;83;33;3;473;448;43|74;83;29;5;477;452;42|66;91;36;4;471;447;43|0;0;0;0;0|0;0;0;0;0|0;0;0;0;0|1;8;73;0.0;0|4;8;74;0.0;0|1;7;74;0.0;0|1;7;75;0.0;0|3;7;74;0.0;0|0;0;0;115"
m[mi++]="24.11.14 07:50:00|0;0;0;0;0;0;0|0;0;0;0;0;0;0|0;19;9;0;586;567;41|0;10;3;0;584;564;42|0;10;0;0;590;570;42|0;19;9;0;584;566;42|0;0;0;0;0|0;0;0;0;0|0;0;0;0;0|1;8;73;0.0;0|3;8;74;0.0;0|0;7;74;0.0;0|0;7;75;0.0;0|1;7;74;0.0;0|0;0;0;0"
// php code to parse min_day.js and insert data into db
ini_set('auto_detect_line_endings', true);
$fileArray = file("min_day.js");
$fileArray = array_values(array_filter($fileArray, "trim"));
$arrayElements = count($fileArray) -1;
$SQL = "";
$x = 0;
while($x <= $arrayElements)
{
$SQL .= "INSERT INTO mydatabase (DatumUhrzeit, Pac_1, Pdc1_1, Pdc2_1, DaySum_1, Udc1_1, Udc2_1, Temp_1, Pac_2, Pdc1_2, Pdc2_2, DaySum_2, Udc1_2, Udc2_2, Temp_2, Pac_3, Pdc1_3, Pdc2_3, DaySum_3, Udc1_3, Udc2_3, Temp_3, Pac_4, Pdc1_4, Pdc2_4, DaySum_4, Udc1_4, Udc2_4, Temp_4, Pac_5, Pdc1_5, Pdc2_5, DaySum_5, Udc1_5, Udc2_5, Temp_5, Pac_6, Pdc1_6, Pdc2_6, DaySum_6, Udc1_6, Udc2_6, Temp_6, Pac_7, Pdc1_7, DaySum_7, Udc1_7, Temp_7, Pac_8, Pdc1_8, DaySum_8, Udc1_8, Temp_8, Pac_9, Pdc1_9, DaySum_9, Udc1_9, Temp_9, SolIrr_10, TmpMod_10, TmpAmb_10, Wind_10, DaySumIrr_10, SolIrr_11, TmpMod_11, TmpAmb_11, Wind_11, DaySumIrr_11, SolIrr_12, TmpMod_12, TmpAmb_12, Wind_12, DaySumIrr_12, SolIrr_13, TmpMod_13, TmpAmb_13, Wind_13, DaySumIrr_13, SolIrr_14, TmpMod_14, TmpAmb_14, Wind_14, DaySumIrr_14, Pac_15, Pdc1_15, DaySum_15, Udc_15) VALUES ";
$string = $fileArray[$x];
$string = str_ireplace("|", ";", $string);
$data=explode(";", substr($string,9, strlen($string)-11));
$SQL .= "('" . DateTime::createFromFormat('d.m.y H:i:s', $data[0])->format('Y-m-d H:i:s') . "', ";
for ($i=1; $i<= 85; $i++){
$data2 = explode(";", $data[$i]);
$SQL .= "'" . $data[$i] . "', ";
}
$SQL .= "'$data[86]'); <br>";
$x++;
}
// connecting to db and executing mysqli_multi_query....
You can setup proper primary keys and use the insert on duplicate...update syntax:
--Say A and B together was the primary key.
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
-- Row will be inserted with A=1, B=2, C=3
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
-- Row where A=1, B=2 will be updated to C=4
Second insert would not give an error but would rather result in the value of C being updated on the already existing row.
In your case, you can update the timestamp:
INSERT INTO table (a,b,ts) VALUES (1,2,current_timestamp)
ON DUPLICATE KEY UPDATE ts=current_timestamp;
To create a primary key on a table that already exists:
alter table tablename add primary key(field1, field2);
To create a primary key on a new table:
create table newtable ( x int, y int, z varchar(50), primary key(x,y) );

Message always appears in first row?

I have a delete function within a function where if the user clicks on the "Delete" button, it displays a message stating that a file has been deleted. The code which does this is below:
$("#imagemsg").html(data);
But the problem is that let's say that I have 4 table rows and I delete a file in the 3rd row, the message should be displayed in the 3rd row only but instead it is displayed in the first row. Another example is that let's say that I have 8 table rows and I delete a file in the 6th row, the message should be displayed in the 6th row only but instead it is displayed in the first row.
Why is the message that is suppose to appear after a file is deleted is always displayed in the first row and not within the row the file has been deleted from?
Below is full code:
var counter = 0;
counter++;
function stopImageUpload(success, imagefilename){
var result = '';
if (success == 1){
result = '<span id="imagemsg'+counter+'">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
}
else {
result = '<span id="imageemsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
var image_file_name = $(this).attr('image_file_name');
jQuery.ajax("deleteimage.php?imagefilename=" + image_file_name)
.done(function(data) {
$("#imagemsg" + counter).html(data);
});
$(this).parent().remove();
});
return true;
}
Below is the deleteimage.php script where the delete message is retrieved from:
<?php
$image_file_name = $_GET["imagefilename"];
echo "$image_file_name was Deleted";
unlink("ImagesFilesFolder/$image_file_name");
?>
The problem seems to be this:
.done(function(data) {
$("#imagemsg" + counter).html(data);
You set counter like this
var counter = 0;
counter++;
But you never seem to refer to the variable again. In any case, this variable is global - the command above will always target the ID with the current number of the counter, so it will not target the tr corresponding to the clicked button.
Since you use
$(this).parent().remove();
I assume that the parent is the tr concerned? In this case you could use a class instead of an ID 'imagemsg' and then do
$(this).parent().find(".imagemsg").html(data);
This would target the message inside the same row of the button.

Categories