I have table user where id = primary key, lastchange = int with lastchange data (in seconds). And i have frontend page with js script. Also all users placed in div like table by pages. So, items has user id and used changed timevalue in attributes.
I want to request all changed user ids in 1 request (1 http and 1 sql). They can be changed by other user on site.
How can i do this? I dont want check every user in page by timer, there is too many requests.
In my mind it looks like:
js do get request with list of users in page in json format [{"id":1, "lastchange":123123},{"id":2, "lastchange":123123}...
Php does request in mysql like SELECT * FROM `users` WHERE `id` IN (1, 2, 3) AND `lastchange` NOT IN (123459, 123456, 123459); (this not works fine, there is no queue for lastchange, it checks all inside braces and result are wrong)
Php return only ids of different rows [1, 15, 22] etc. to js.
Js check every id separately in other request getting full info about user by id
I can check every user in php separately, but i want to know how can i do it with 1 SQL request
Sorry my bad English.
I think you might want to implement the solution differently as per the first comment.... but, if you want keep your current model the SQL you need would look something like:
SELECT * FROM users WHERE
(id = 1 AND lastchange <> 123123) OR
(id = 2 AND lastchange <> 123123) OR
...
This will keep the id's and the lastchange values that relate to each other being compared properly. It is pretty ugly SQL but not hard to generate in a loop.
Sorry my stupidness. I think i solve this.
Js request api with only user id in page
php response json like id, lastchange
js checking lastchange value and id in page
js request full data about changed user replaces old in page
Thx all for helping
Related
I am currently upgrading my livechat system to use the append function with JavaScript.
And in order to get it to work I will need to get the latest chat date or ID somehow.
So I can then do a query like:
SELECT date, message, name FROM chat WHERE id > $lastPostId";
This will then allow me to append all the latest messages instead of updating all of the HTML everytime there is a new message
So basically, my chat right now works like this:
Every second it checks for my PHP file, loadchat.php.
Loadchat.php will get every single message from the database
It then replaces all current data in my div: #chatbox by using .html() function.
And I want to change it to the append function in jquery allowing it to run a lot smoother
Because it only needs to read everything the first time and then append
So my question is, how do I get the last post ID?
Case 1:
Add one more field in your database called timestamp. When you update the chat you can store the value of last timestamp in session.Now each time fetching a new chat just send that timestamp to loadchat.php and query the db to fetch rows where timestamp > stored_timestamp.
Case 2:
You can take a flag in db like is_read. When you insert the new chat the default value of is_read will be 0. When you fetch the data just update the flag i.e is_read = 1. Now in your query you just have to check for the flag.
where is_read = 0.
It will fetch all the unread messages and will do the job.
Hope it will help!!
I am continuing to work on my multi stage bootstrap form, and I have hit a roadblock trying to pull info from my DB.
The main page is PHP and is named quote_tool.php
I have the following functional requirements:
The data must come from the MySQL database.
The user should only receive data that they requested (i.e. a row from the db with info about user license should only be grabbed if the user checked a radio button to include user licenses on the form).
The information needs to be called from the DB without refreshing/reloading the page.
Currently I have a table in my DB with the following columns:
There are 3 different products in that table right now. The user can select a radio to say they want to include endpoints, and then there are 3 check boxes to allow the user to input a quantity for which endpoint(s) they want to include.
The input field looks like this:
<label for="device-9102" class="form-partner-label"><input type="checkbox" class="quote-chkbox" id="9102-chk"> 9102 IP Phone</label>
<input type="text" name="9102-quantity" class="form-endpoint-qty form-control" id="form-partner-9102" readonly value="0">
When the user checks the box and input a value this value is dynamically updated on the summary page as well in the following field:
<input type="text" readonly name="sum-9102-qty" class="summary-field sum-qty" id="sum-9102-qty">
There is also 2 other fields on the summary page regarding this product.
MSRP
Part Number
MSRP is a hidden field that will be used for additional calculations, but Part Number is visible on the summary page.
When the user inputs the value for the endpoint quantity I need to call the DB and pull the MSRP and Part Number from the refEndpoints table.
I am currently building a function to call the DB when the user hits the "Next" button on the form, and that looks like this:
//Call DB to fetch part number and msrp of 9102
$('#form-partner-9102').change(function()){
var quantity_9102 = $('#form-partner-9102').val();
if(quantity_9102 !== 0) {
}
});
This is the point that I am stuck at. I am not sure how to call the DB and place the values of the part number and the MSRP in the correct input fields on the summary page.
jQuery runs on the client side so it cannot connect to MySQL directly, however your question is tagged php, which runs on the server side and thus can connect to your database. First you will need to setup a PHP file that can respond to HTTP POST requests and return JSON. Here is a great answer that shows you how to do this: Returning JSON from PHP to JavaScript?
Once set up (and you will need to workout what parameters this PHP file takes in and how it converts this into a query so that it can respond) you can now setup some simple JavaScript to call this PHP file (lets call it query.php). Code that does this might look like this:
$.post('/query.php', {quantity: $('#form-partner-9102').val()}, function(resp) {
$('#PartNumber').html(resp.PartNumber);
});
Some important things to keep in mind are to always be sure to use prepared statements when taking user input and turning it into a query (don't just build a SELECT statement by joining strings). Also be sure to look at your event binding, you can probably write one generic handler for your inputs that takes the partner ID as a data-* attribute making your code smaller and easier to maintain.
Im using AngularFire+Firebase and have data at firebase-database.
Im trying to paginate Data with Smart Table
My problem is that I dont know how to range query without specifying any child i,e fetch records from record # 25 to 35
Below query gives me first 5 records
var queryFIrst = visitRef.startAt().limitToFirst(5);
$scope.Visits = $firebaseArray(queryFIrst);
now Im trying to get records next 5,from 6 to 10 and I tried below
var queryFIrst = visitRef.startAt().limitToFirst(5).endAt().limitToFirst(5);
$scope.Visits = $firebaseArray(queryFIrst);
but it giving error that startAt and endAt can't be used like this with limit
In general pagination is not a good fit for Firebase's realtime data model/API. You're trying to model a SQL SKIP operator, which won't work with the Firebase Database.
But if you want to model pagination in Firebase, you should think of having an "anchor point".
When you've loaded the first page, the last item on that page becomes the anchor point. When you then want to load the next page, you create a query that starts at the anchor point and load n+1 item.
In pseudo-code (it's real JavaScript, I just didn't run it):
var page1 = visitRef.orderByKey().limitToFirst(5);
var anchorKey;
page1.on('child_added', function(snapshot) {
anchorKey = snapshot.key; // this will always be the last child_added we received
});
Now when you want to load the next page of items, you create a new query that starts at the anchor key:
var page2 = visitRef.orderByKey().startAt(anchorKey).limitToFirst(6);
A few things to note here:
You seem to be using an approach from the Firebase 1.x SDK, such as an empty startAt(). While that code may still work, my snippets use the syntax/idiom for the 3.x SDK.
For the second page you'll need to load one extra item, since the anchor item is loaded for both pages.
If you want to be able to paginate back, you'll also need the anchor key at the start of the page.
Is that what you needed that time?
visitRef.orderByKey().startAt("25").endAt("35")
I asked a similar question Get specific range of Firebase Database children
So, there are 3 urls:
example.com/first
example.com/middle
example.com/last
In my sql db, there is table with each terms that correspond to related posts:
ID NAME POSTS
1 first 12,3,343
2 middle 23,1,432
3 last 21,43,99
So if an user visits example.com/first, then I want to show posts of "12,3,343" and other posts based on what url they are visiting.
Now, this is the sequence how it would work in my head:
User types "example.com/first"
js (ajax) or something detects the url (in this case, detects "first").
the term is sent to php query.
Gets appropriate info then sends it out (either by ajax or something else).
Am I approaching this right?
How does the server detects what url was requested? I supposed I can skip the first two steps if I know how the server detects the url and I can query the correct info directly instead of relying on js to detect it.
Thanks!
When you mention ajax, I assume you are not navigating away from the page your are on. Am I correct?
If so, you have to create another php file to respond to the requests:
A request is sent to file.php with the url as a query string
In file.php, let it query the DB and json_encode the data.
Retrieve the data and update the fields without navigating away.
PHP is only executed once (Server-side). if you want to execute another query you have to either navigate to other URL or just send your request to a php file via ajax.
You can get the segments of a url request using below statements
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $url);
Now you have all the segments in an array ($segments)
print_r($segments) to get the index of the segment you require.
Now compare that segment with your value
For Eg :
if( $segments[2] == 'first')
{
//Your Piece of code
}
Hello people
I'm trying to figured this out, but I still can't do it.
I have a rails 3 app, I'm working with invoices and payments. In the form for payments I have a collection_select where I display all the invoices number (extracted from a postgres database), and what I'm trying to do is when i select an invoice autopopulate others text_fields (provider, address, etc.) without reloading the page, in the same form.
I know I should use ajax, js, jquery, but I'm a beginner in these languages, so i don't know how or where to start
hope you can help me... thanks
What you are going to want to do is route an ajax call to a controller, which will respond with json containing the information. you will then use jquery to populate the different fields.
In your routes:
get "invoice/:id/get_json", :controller=>"invoice", :action=>"get_json"
In your invoice_controller:
def get_json
invoice = Invoice.find(params[:invoice_id])
render :text => invoice.to_json
end
In your invoice model (if the default to_json method is not sufficent):
def to_json
json = "{"
json += "id:'#{self.id}'"
json += ",date_created:'#{self.date}'"
... //add other data you want to have here later
json += "}"
end
In your javascript file,
$("#invoice_selecter").change(function(){ //calls this function when the selected value changes
$.get("/invoice/"+$(this).val()+"/get_json",function(data, status, xhr){ //does ajax call to the invoice route we set up above
data = eval(data); //turn the response text into a javascript object
$("#field_1").val(data.date_created); //sets the value of the fields to the data returned
...
});
});
You are probably going to run into a few issues, i would highly recommend downloading and installing fire bug if you are not on google chrome.. and if you are, make sure you are using the development tools. I believe you can open them up by right clicking and hitting inspect element. Through this, you should be able to monitor the ajax request, and whether or not it succeeded and things.