Creating a Database that can be updated live - php

This is very hard to explain but I'm going to try.
We run a motor shop that has a QC program. The program was coded in access97 and it's time for an upgrade, we have elected to try a PHP/MySQL approach to do this.
Right now the access software has several pages to the form and each box sends to the database live so when you type something in you don't have to hit a save button or next or anything and when you come back it's there.
Also the forms are driven by an auto-incremented job number that you can punch into a field at the top of the page and it query's the server and displays all the data in the form boxes so you can edit it.
I don't know how to even start this project. I got a working form and an insert.php page but I don't know how to go about the rest.
If I could get a pointer in the right direction that would be appreciated. Thanks!

You just want it to save automatically? You'll have to look into JavaScript, and more specifically AJAX. I recommend using the jQuery library. Basically, you're going to want to make an AJAX call every time your form field is modified, and that AJAX call will simply update one field in particular.
I understand you are likely very new to website design, so this might be complicated for you.
I would read through this W3Schools tutorial. After reading through that, I'd pay close attention to this tutorial.
Again, this is difficult for beginners. I'd recommend you continue to work at your script, and ask more specific questions here on StackOverflow as time goes on. Good luck!

I have created a simple example here:
HTML/JS:
shaquin.tk/experiments/ajax.html,
PHP: shaquin.tk/experiments/qc.txt.
Have a look at the source to see how it works (I also have some comments in my code), feel free to copy it and modify for your own needs.
To sum up how it works:
When text is typed into a text box, a list of changed elements is updated.
Every updateInterval milliseconds (default 1000), the list is checked. (This helps reduce traffic and lag.) If anything has changed, the PHP file is called to update the database, and the list is cleared.
If an element loses focus and it has changed (e.g. copy/paste), the PHP file is called.
The PHP file sanitizes the query, checks for a valid job number, and updates the database.
References:
AJAX XMLHttpRequest
setInterval
addEventListener
encodeURI
mysqli_connect
mysqli_query
mysqli_real_escape_string

You'll need to submit the data as an ajax request. That way the data can be sent and returned without the page needing to be reloaded to update the information.

Related

HTTP request via AJAX or form-submit. Which one should I choose and why?

I have a PHP page with a simple form. One input text field & a button. Input text field accepts user queries & on button click an HTTP GET request is made to the server & the result has to be shown back in the same page containing the form. That's too simple to do. I can do this in two ways. One is AJAX & other one is the good old sodding form-submit method.
My question is simple- Which method should I use? Since both of the roads lead us to the same place, which one should I choose to travel?
First of all, let me talk about form submit method. I can use <?php echo $_SERVER['PHP_SELF'] ; ?> as the action of the form for submitting the values of my form to the same page. Once I store those values into some random variables, I can make a GET request & obtain the result & show it to the world. This method is easy to use. Happy Down Voting to all of you.
Or I can make a GET request using AJAX and jQuery or JavaScript or whatever you wish to use & obtain the same result as in the previous case. Output is same. Only the mode of execution is different.
So which one is better? Which one fetches result faster? And why should I use that? Is there any difference? GET, POST, PUT or whatever- it doesn't really matter. AJAX or form-submit?
There shouldn't be any significant, genuine speed difference between them.
The Ajax approach will load a smaller amount of data (since you aren't loading an entire HTML document), but by the time you take into account HTTP compression and the fact that (if your system is sensibly configured) your dependancies (images, scripts, stylesheets, etc) will be cached, it won't be significantly smaller.
By using JavaScript to create a loading indicator and not refreshing the entire window in front of the user, you can create the illusion of a faster load time though. So if feeling faster was the only concern, then Ajax is the way forward.
Using JavaScript, however, is more complicated and slightly more prone to failure. The consequences of failure states are more severe because, unless your code detects and does something with them, the user will (not) see it fail silently. For example, if a normal page load times out because the user is on a train and went through a tunnel, they'll see an error page provided by their browser suggesting that they refresh and try again. With Ajax, you need to write the error handling code yourself. This does give you more flexibility (such as allowing you to simply try again a few times) but the work isn't done for you.
The other consequence of using Ajax is that the address bar will not update automatically. This means that the results won't be bookmarkable or sharable unless you do something explicit the make that possible. The usual way to do that is pushState and friends, but again, it is more work.
You should also make the site work without JavaScript so that if the JS doesn't run for any reason then the site won't break completely. If you use pushState then you have to do this for the URLs you are setting the address bar to point to to be useful.
The short answer: Use a regular form submission, then consider layering JavaScript over the top if you think it will give your visitors a worthwhile benefit.
I Should stick to an Ajax request when possible.
This because you then don't really have to load every single item on the page again ( like all the images, menu and so on ). You can just give the relevant HTML back and JQuery can place it inside the relevant holder.
But that is just my humble opinion...
If you have to retrive simple data from server without reload the page my advice is use jquery .get o .post
also it provides you a very large API that allows you to reduce your programming time.
http://api.jquery.com/
obviously the execution time increase but in my experience the user cant fell the differce with a simple ajax request.
so in my opinion if jquery allow you to obtain the results, this is the best solution because halves your work time!
See the edited one it may help you.
I think that AJAX should be used for displays updates and form submissions should be done via a page reload. Reasoning?
When submitting forms, you are telling the application to do something. Users tend to want to feel that it was done. When a page doesn't reload, users are often left wondering "Did that work?". Then they have to check to make sure what they did was right.
but when you are displaying a table or something, and the user says to "display x data....now x1 data" for instance, they aren't "doing" something (creating new entities, sending emails, etc). So AJAX can provide a nice user interface in this case. Page reloads would be annoying here.
In conclusion, I think form submission should be done via page reloads (let the user see it working), whereas display updates should use AJAX (prevent annoying page reloads).
Of course, this is a preference thing. Some of my company's applications use AJAX all over. But those are the applications that are the most difficult to maintain and debug. ;)``

I'm passing php variables to javascript. Is there a better way to structure this?

So I'm writing a webpage that has a series of slot machines. You press on a particular slot machine and it tells you how much you won (or lost). I want to change these values a lot so I'm reading them in from a file using php so I can easily change the file to change the behaviour of the slot machines. (the file is just a bunch of numbers, eg "14,-3,6,9,-12,etc"
Now the way the slot machine works, as you can imagine, is that when you press on the machine, a value appears on the slot machine indicating what payout you get. And then a running total is updated by adding the value that just appeared in the slot machine. I am using javascript to achieve this affect. But in order to change the value of elements on the page, I need to know what to replace the elements by. So I'm thinking of sending all the data through to the javascript side of things.
But I've read many times that this is bad practice, and people usually ask "What are you really trying to do?". So this is what I'm really trying to do, manipulate values on a page, based on values in a file on the server. Is there a proper way to achieve this?
The better way is of course AJAX. You will be able to use the server values and update page content simultaneously. I would prefer using AJAX with JQuery as it takes care of cross browser issues and makes it easier to bring data from server as well. Here are some fairly simple tutorials about using AJAX with JQuery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
I am not clear how exactly your site works. But I think you can use ajax to do this.
When a user click a machine, javascript send a request "in the background". That is, using ajax. And then you can get the data returned by this request. Then you update data on your page. Have a look at Jquery ajax.

Refresh a page after data in MySQL database changes

Good day all,
Basically what's I've got is a PHP based site tied to a MySQL database all on a local web server (nothing is being accessed from outside of the company). The index page displays an image resembling a bar chart. Employees of the company will be entering data periodically which will update the image that appears on the index page. The index page will be displayed on a couple different screens throughout the company and I need that index page to refresh after someone alters the data in the database.
I've been messing around with various AJAX solutions, but as I don't know much about AJAX I'm having trouble adapting something to work the way I need. Here's the way I've was thinking about:
-- on the index.php run a JavaScript function every minute or so that gets a response from dataChanged.php
-- dataChanged.php will query the database and get a timestamp from one of the tables.
-- the script on the index.php will then compare the timestamp to the last time the page was refreshed (or some variable that stores such information) and refresh if the data is new.
I'm somewhat proficient in PHP, but am very limited with JavaScript (and thus AJAX).
Can someone get me pointed in the right direction?
Thanks!
What you want it the standard javascript function setInterval
Have it execute a ajax call every now and then to get new data. Try to get a standars librabry that knows this stuff, probably jQuery
Depending on if the chart generation is time consuming or not I would go with different strategies. The preferred way would be to just generate the graph on each call, but if that is very time consuming I think your two-step solution works great.
Check out the link http://blog.codebusters.pl/en/auto-refresh-content-after-changes-in-database-ajax.
Here you can see how to refresh your page after change in db.

Adding multiples of an item to a form, without javascript?

Thanks everybody. (For some reason I couldn't up vote answers, so everyone wins today :] thanks again!)
Complete php and javascript novice here, apologize up front for anything half-witted.
I have a portion of a user's profile in which I'd like the user to be able to add additional items of the same thing, with slightly different conditions.
For example, let's say it's favorite books. A fieldset contains some checkboxes for genre and an input text box for the title of a book. After the user checks a genre and fills in a title, they can add the book to their set of favorite books and then have the option to add another. When done adding books, they move on to the next fieldset, complete the form and submit.
How is this done? And more-importantly, is it possible without javascript?
Without JS, I understand this probably entails a lot of reloading of the page to add the items, regardless I'm more confused about how the $_POST data is handled, both before and after the submit.
Sorry for such an open ended question, really just looking for someone to point me in the right direction, as searching for this topic proved to be a bit difficult.
Thanks.
Some Clarification
I'm trying to develop an application that is as independent of javascript as possible. In that sense, I don't know if it's possible to add the new items with PHP alone. My sense is the fieldset in question could have it's own submit button, the action of which POSTS to the page itself (no DB interaction, etc), and variables like $book_genre1, $book_title1 are populated in the page. Then, the "official" submit is sent later, which actually adds the POST data, which contains the books array, to the DB. But I don't know if that is a safe procedure or good logic to begin with.
In reply to the above answer, if that is exactly what you need since I seem to have a different idea.
You simply store each addition in an array stored inside a session variable, and in each page load, parse the data into readable html.
$_SESSION['form'][] = serialized_form_data;
On each load,
foreach ($_SESSION['form'] as $form) {
unserialize_data_and_create_html();
}
add_new_form_element();
I'm assuming you want to show the user already filled forms so he can deal with them as he wishes.
This is a better implementation than what I thought of earlier. I wanted to implement a db version.
Sorry for the delay. I can't comment since I'm mobile (js issues) so I decided to edit instead.
You can simply use the $_SESSION['form'] for your inserts.
A simple foreach will work as well. However, remember to sanitize each value properly before inserting it. That's the key.
If you use prepared statements with binding, you have the advantage of clean input as well as better database performance.
What you're really asking is how to persist information between POSTs of the same form. The most common and effective way of doing so is to just use the inputs on the form. If you have information that shouldn't be displayed then use hidden input elements for them.
Note that storing information in the form like this is not considered secure since it can be manipulated and/or forged, so the next option is to store it in the session; since it is server-side only the cookie/session ID needs to be protected. The values can then be retrieved from the session in PHP after the POST has occurred.
Before you submit a form...there is no data to handle. Once a form is submitted data then is sent to the server in the form of an array.
(From php.net/manual/en/reserved.variables.post.php):
$_POST = "An associative array of variables passed to the current script via the HTTP POST method."
So a user submits some data to the server. Now that data is available to your scripts for use: Populate a database, validate the values before doing "x", write HTML to the client, etc.
I like where #frosty is going with his approach. It does potentially send multiple requests to the server, but it's also a very straight forward approach. A completely server-side solution.
JavaScript or the jQuery Library would allow you to accomplish a similar result, and post to the server just once - by simply hiding/showing populated fields, writing additional fields to the form dynamically (eg: After completing "book #1" the user can click "Add another" and JS writes an identical set of form fields all referencing book #2). Obviously, this approach will get more involved than a straight PHP approach. And you'll need a backup plan if you want to allow users with JS disabled to participate.
I would suggest you use javascript to handle the user adding multiple items. Check out jQuery (http://www.jquery.com) which is a fantastic javascript library that will help you do lots of great dynamic things.
Then once you have all of the information from the user, just once it all at once to your php and save it. For information about to access and use $_POST or $_REQUEST, you'll need to check out some PHP tutorials or pick up a book. That's fairly basic PHP stuff and too large a topic for this thread.

Ajax or jQuery page reload with new data added to sql database

I'm totally new to ajax, but pretty good with PHP. I have a PHP page which currently refreshes every 2 minutes because it has to check for new data in the sql database. It's pretty annoying if you're using it and it keeps refreshing. The database is updated about 3 times a day, but what is shown on that page needs to be kept current with what's in the database. I'm trying to find a way to have ajax or something check the database every 30 seconds or so, and if there is something new, then refresh, but if there isn't anything new don't refresh. Does anyone know of any tutorials out there, or something that can get me started? I have the concept down I think... I just can't figure out the code. I'm sure if I get it to check the database I can figure out the rest.
Thanks in advance!
Check out jQuery. It makes it super easy to retrieve a remote resource in the background: $.get(url, callback). The contents of the page should be in either XML or JSON. I suppose you already know how to generate these using PHP.
Once you've retrieved your updates (or lack thereof), you can decide what to do with it. Again, with jQuery it's very easy to append to or replace the contents of any part of the page, without ever refreshing anything. $("#id").html(new_html)
And that's just the beginning. You can do a lot more than that. Welcome to the world of AJAX!
Of course, you can do AJAX with vanilla JavaScript. But then you have to account for all the different browser perks, so I highly recommend using a framework such as jQuery. It also comes with a pretty comprehensive online documentation and some examples, so try them out.

Categories