Is it possible to create and run a thread in PHP? - php

When a PHP page is displayed then I want to start a thread searching for the last value entered in a MySQL table column so that the value of a text input field should be this last value incremented by 1 (it's a number). I want a thread because the page may be displayed for a long time and during that time the column may has been updated many times, so I want to get the value each period of a time interval. When clicking the submit button then the value should be last one in the column. Is that possible ?
Consider this scenario :
one user displays the page , so the field contains the incremented value. Then another user displays the same page, so the field contains also the same incremented value. When they submit the form then there is concurrency problem because they submit the same incremented data ! So how to resolve that situation ?

one user displays the page , so the field contains the incremented value. Then another user displays the same page, so the field contains also the same incremented value. When they submit the form then there is concurrency problem because they submit the same incremented data ! So how to resolve that situation ?
You will not be able to keep abreast of all the possible changes to the highest value in real time. An Ajax based solution which periodically fetches the value will not be fast and reliable enough. What happens if the highest value changes in exactly those 100ms that my request takes to make it to the server? What if a user's network connection is temporarily down, he clicks "save", and two values end up overwriting each other?
The usual solution is to determine the highest value not in the user interface, but at the time of storing the record in the database. A way to achieve this effect automatically is using an auto increment field in the database.
If you absolutely need to display the current value to the user, you will need to employ some sort of locking mechanism. Ie. determine the currently highest value, and reserve that value for the current user until they either save the record, or leave the page. But there is simply no way to display the highest current value to every user in a 100% reliable way. You will end up with collisions this way. Like #N.B. says in the comments, you probably should rethink your design.

You can achieve this through AJAX easily by calling the database or a controller asynchronously every 1 minutes for example - or on a particular mouse event perhaps - and returning JSON data or a view with displayed data. Many popular social network sites do this to get the latest feed / data displayed on their home page.
More info on: http://ajaxpatterns.org/Periodic_Refresh

Related

Maintaining search form input

I'm building a CRUD application and need to implement two forms of search:
The basic search function accepts a keyword and searches every column in the database table for that particular keyword. The search keyword is sent as an URL-parameter in the form www.website.com/category?q=keyword. Nothing too special here...
In the advanced search form users can specify up to 5 keywords and for each of those they can select a column from the database table which needs to be searched for this keyword. In short: the advanced search form takes up to 5 keyword-column pairs. This form gets submitted via POST (because i want to avoid hitting limitations on maximum number of URL-characters).
The results need to be paginated, showing 10 records per page. I've searched for pagination classes online, but they all fetch the total amount of records in the database table, and then return the selection that needs to be displayed for that page. Because I'm working with a large set of data here, I can't afford to do it this way.
This lead me to create my own pagination class, which takes the requested page number (and if applied, the $_GET and $_POST parameters from the search forms). Based on that it calculates the total number of results, calculates the total number of pages, decides whether there's a 'previous' and 'next' page... It also returns an SQL statement (with LIMIT and OFFSET values) to be executed by the particular Model (using my own MVC architecture (aka no framework)). This allowed me to only fetch the results for the requested page.
Problem: when the user navigates through the pages (aka clicking 'previous' or 'next' buttons), the $_POST data is lost. However, these values are needed in order to get the results for another page.
This particular problem made me think about the search forms on forums. I submitted a query on one of them and noticed a search ID getting appended to the URL:
example.com/forum/search.php?searchid=5672532
This means that the form data is being kept somewhere, somehow... and I'm thinking what the best option might be, from most to least plausible:
- Database table where each search input gets saved for e.g. 30 minutes
- Sessions
- Files
(hidden fields are obviously not an option, because they need a form submit button to be pressed in order to get sent with the request)
I'd like to here your opinions on this, some of you must have encountered this problem already...
Saving the search parameters in JSON or URL encoded in a database for a set amount of time (have an expiry column) seems the best solution.
Note that in that way, you'll need to query the database over and over, with different LIMIT clauses.

Auto refresh in PHP

I have piece of code which refresh data periodically (after 5 sec.), and put it into a table.
This table has sorting option, and checkbox to select a particular row.
Now problem is when i want to sort or choose a row using checkbox, because of auto refresh it set whole table data in previous position. Means if any data i had sorted will not show sorted and/or checked row will be unchecked again.
Please provide me some suggestion how to handle this issue.
Thanks
Your alternative might be to do an AJAX call to pull the data periodically instead of refreshing the whole page via PHP. That way you'll be able to send the correct parameters to handle the sort towards the logic within PHP.
OR
You can push named parameters/actions within the url for sorting purposes. Then use URL's on the table header and the page reloads with a url of something like:
http://example.com/table/sort:asc
http://example.com/table?sort=asc
And then your logic could appropriately pick the previously selected areas up.
if (isset($_GET['sort'])) {
//Do sorting stuff
}

how do retain value of dropdown box in php

I will try to make it simple as possible. I know how to select a default value in dropdown. My problem is how to make the last option in the dropdown as default "interactively" for next time. so that means that I cannot hardcode the default value.
Lets say I want to multiply 2 numbers. I have two drop down boxes and contain number 1 to 10; at the very first time it will say 1 and 1 since if no default is mentioned, then the default is the number at 1st position. Lets say if somebody picks 2 in the 1st and 6 in the second. Once the user hits calculate, the page will refresh, the answer 12 will be displayed. I still want 2 and 6 stil to be there, and NOT go back to 1 and 1
Please note that if I have action set to "answer.php", and display the answer on a new page and have a back button to come back to initial page. There is no problem. but I don't want that. I want to stay on the same page.
I am not using mysql. All have is a simple for loop and I dynamically load values 1 to 10
I believe I need something like selected = ?????? please fill the blank and where would I put this in the for loop
I have spent whole day on this on google but no luck to what I want
Thanks
Amit
As I see it, there are several ways to do this:
On the page that receives the form data, check which option the user selected and store it in a cookie. When you generate your form, check if this cookie is present; if so, use its data as the default value. This is probably the simplest option.
Store the selected option in a PHP session variable. This will work the same way as #1, except default values will not be saved if the user closes his browser.
Use a login system and store the default value in a database.
There are many ways to do this, the differences come down to how 'deep' you want the storage to be. Without wasting too much time here is a quick list of storage options:
POST vars (this is the solution that best suits your scenario)
Cookies
Session
Database
Server Filesystem
etc etc
Basically the simplest technique is to take the data that is passed and redisplay it, so for your form you have 2 inputs, leftval & rightval, the user hits submit on the form and you multiply them to show the result.
When you build the page to show the result use the $_POST['leftval'] & $_POST['rigtval'] to populate them on the new page. Make sure to sanitize the values and escape them on the way out!

How to store the form data in a MULTIPAGE form?

I am trying to develop a registration page which involves three separate information.
First Page will get contact details
Second page - working details
Third page - study details.
How to keep the form data of the previous pages before posting the form?
You could do it with Ajax - multiple divs and hide/show the appropriate ones.
Or you could POST each page and save the data in the $_SESSION global variable until all pages are complete. Then save it all to the database.
While the other answers are certainly good ideas, you may also want to consider persisting the intermediate data to your database between each page. So, submitting the first page would create the new row, with the columns relating to contact details populated, and a status column set to a value indicating that the submission is not yet complete.
The second page would update that record in the database. The third page would also update the record, as well as the status flag to indicate the submission is complete.
The main benefit to this is that the user can walk away after the first (or second) page, and then return to it later, even if he had closed his browser and his session had expired. (As long as he has a unique URL to return).
This approach might not have a lot of benefit if you are only collecting three pages of data, but if you had many pages, the ability to leave and return later might be more important.
You should take a look at http://jqueryui.com/demos/tabs/, it should be able to do what you need.
While shifting to another page, you just put the values of first page variable in sessions, then you can access the value of previous page at any page, then post the value to the database query. In this way, you can use the use the value of first page at third page, up to when browser is open. As the browser close then variable lost their values.
Back in the day, I would've put hidden fields for all of the previous pages in each subsequent page, so the final submit would have everything... i.e.
Now, I would probably only have one actual page.. with multiple steps implemented by showing/hiding div's and collecting all of the data in one big form, broken up visually for the user... and if I was feeling especially frisky, with frequent validation and final submission through ajax.

Mapping javascript objects to their ids in an MySQL database

This is a question that I have been pondering for a long time, but didn't want to ask because I wasn't sure how to describe it.. I'm still not sure if I can describe it well but here it goes..
I have a web app that allows you to manipulate a bunch of elements on the page, but has one save button. When I hit save I would like to create/update all of these changes in one POST (not incrementally). If these html elements were created for the first time on the page, I would like to insert them as new entries into the database. When these changes are saved in the database for the first time (created), I return the index ID, so if I make changes again, they will be updated in the database instead of created again.
What makes it tough is batching this save so it doesn't take up all this bandwidth. I want to be able to mix and match creates and updates, but sending back IDs from the created elements and mapping them to the correct html elements (so they will be updated next time) requires me to know something about the order of each batched element which leads to some issues. I was wondering if there is a clever way to do creates or updates, and map the IDs correctly back to various elements under one ajax request.
Hopefully this was clear, let me know if you need clarification
Thanks,
Matt Mueller
You can just use negative auto-decremented ids for newly created elements and return a map from negative to positive ids. E.g., send [{id: 507, name: "foo"}, {id: -1, name: "bar"}, {id: -2, name: "baz"}], return {-1: 510, -2: 511}, and have your javascript update its ids based on the map.
well, upon loading, fetch next ID from db, so you know, what ID will have next page part in database. then, upon creation, in javascript you can work with this - i.e:
Next ID is 15, so when you add next field, it's ID is 16 and there is ID 17 in stack... and when you delete one newly created field, isn't problem to shift every higher ID one down.
Then, in your saving script, you know, that every ID larger than what you previously fetched is "to be saved" and every smaller is to be updated.
If your page knows when a new element is created, then it should arrange for the "id" parameter for that group of parameters (i.e., the attributes of the entity to be added) to be either null (not supplied) or some marker value. Already-existing entities have their ID value, which would not be changeable by the client. The server simply has to separate out the groups of parameters with empty ID values from those with non-empty values.
Your client may also want to mark elements for deletion. In that case, the already-existing entities would have their ID sent back with some flag parameter indicating "DELETE ME". Entities that are created and then deleted before "submit" would need no server processing.

Categories