How to avoid some SQL queries in PHP? - php

I am developing a PHP web app with jQuery and Twitter Bootstrap. And it uses AJAX for everything. So, I show a form in HTML5, the user press a button (class="btn"), the form is sent to PHP (jQuery, AJAX), PHP makes a query to the MySQL and echoes an answer, which is shown in the form (jQuery). This is basically how the web app works.
But here's the deal, the first form it is showed, it's a div that shows some news. For example:
A new user was created.
There is new important date.
Someone wants to text you.
So I've created a table in MySQL called News where I saved some values than mean something like:
1: A new user was created
...
Everytime the user log in will se that. It means that there will be a query and a response as soon as the HTML5 get loaded when a user log in.
The index.html file has a navbar (Bootstrap), and a option call News. When the user clicks it, the same query will be executed, but not necessarily the same response.
I thought in modifying the div with news whenever the user does an action. But, an action can also be done by another user. So it is necessary to make the query again!
Is there any solution that allows me to avoid querying the database when the user wants to get the news? Or how can I know that it is necessary to update the div right now? I was taking a look at caching queries but didn't arrive to a conclution.
Sorry if my english is not too good, it is not my native language.
Thank you.

You can send a timestamp in every news response from the server and save it in javascript. The next time you make a request, send the timestamp you saved and the server checks if there are more recent news, sending nothing if there is none as the last response is still the newest.
Well, there is a downside here, you still need to make a query to the database (filtring the results with a WHERE clause like 'WHERE ... TIMESTAMP > last_timestamp_from_browser') which is perfectly valid, SGBDs are designed for this, and if you don't have thousands of users accessing your website at the same time there will not be any problem. With this approach you will only save bandwitdh as the connection to the database is still made.
There is another way that prevents this connection from being made, cache some values of last news inserted which could be user specific or global and save them in APC module (or memcached). You'll need to discover what to cache and when (you can't cache the entire database, just some well organized timestamps and maybe the most requested news for example). This way you prevent the database connection from being made. This will force you to do many many more code, so, use it only if you really need it, like thousands of user connections at once.

Related

deny access to data(a video) when hitting back button on browser

Im doing a quiz (php and mysql) for some students, the quiz is based on a video they have to watch..
the order is this..
1)they enter a unique web page for every user
2)access a page with a video for the user to watch...
3)on the bottom of the page there's a button "Answer Quiz"
4)When they click the button, they are send to a page with the quiz
Here's where the problem happens, i want to prevent the user from watching the video again, but when they hit the back button, well there's the video again for them to watch
im blocking the video in a video table in mysql db, but the video is cached or something, so this is not the approach of preventing the user to watch the video again when hitting the back button...
.
any ideas of how to achieve this??
any help appreciated......
Checking from your latest comment, I would assume that you have a table, expired_quizzes with at least three columns, quiz_id, quiz_filename and the boolean is_active. I would also normalize the table to a userid as well, so if user A views it and takes the quiz, user B can still see the video (makes cheating with a friend easier, though). It is hard to know exactly what is going on without seeing any code or structure, but try checking a couple of these things:
If you look up the quiz based upon a search, and the webpage uses a variable $_GET, then anytime the webpage is visited, it will always load the quiz. So considering:
http//www.yourwebpage.com/?quizfilename=viewablequiz.mp4
Depending upon your PHP instructions, it will always load viewablequiz.mp4. There are two recommendations to prevent it.
Don't load $_GET['quizfilename']. Rather load $_GET['quizid'] and recall the filename from the query with additional search parameters, such as:
'SELECT * FROM expired_quizzes
WHERE quiz_id='{$_GET['quizid']}' AND is_active=1
LIMIT 1;'
Then, return row['filename'] in your PHP code, or handle with a response to the user if no results are found (no unexpired quizzes).
Load the video via AJAX. Use a similar query on the PHP side as mentioned above, but since it requires a look-up after loading, a refresh of the screen will not load anything.
To prevent cheating, you should probably also have another table which records every time the video is viewed, with a timestamp and userid. It can help detect a cheating attempt later by seeing who was testing and viewing at the same time.
Of course, always protect against SQL injection and don't put user input directly into the SQL statement.
For a more detailed analysis, you should post just the relevant PHP, HTML and SQL within the question.

php form submit counter

So I've made an extremely simple 4 page static webpage for this client with a quick contact form handled by php. Everything goes swimmingly.
Then the client comes to me and requests that he is able to see a counter of how many submits have been made. So he generally wants a counter for his form, Which is simple enough because I just add a counter for every successful email sent using the form and save it within some kind of data storage.
BUT...
the only way I can think to do it is have a separate user page with a simple box that has the number in it, that only the client can access.
I could do this... Save the counter in an xml file or a one table, one column, one row mySQL database.
But is there a better easier simpler way to do this??? Can I set up a link with Google analytics or something? Rather than making a single page with a number on it.
I suggest going with a separate page for the client to view counts. You can use .htaccess to control the access to this page. The main reason is looking forward to future client requests. Most likely, they will then ask you to show counts for specified periods of time, counts per day/week/months, etc. If you set up your page now, then you can have place to customize/extend.
As for storing the counter, I would suggest storing more than just the total. Have a table where you'd store:
date/time of form submission
remote IP address (for possible future reference)
content of the submitted form (if the client ever decides to want to see it)
maybe event content of the email (if the client ever decides to want to resend it)
Then to display the totals, you'd just select count(1) from that_table with any required date/etc. grouping.

how can I refresh a webpage using ajax, after database inserts

I have a service running on a pc witch does some inserts in my (MySQL) database. What I want to do is everytime a new record is inserted in database to refresh automatically my webpage (I am using php). I read a relative post about updates
refresh the webpage on database update, but those updates were done "from" the webpage.
I also read another post
https://stackoverflow.com/questions/6460297/automatically-refresh-the-webpage-just-after-a-new-database-entry, didn't figure out how I can do this.
Any suggestions?
This is how you do it
Use JavaScript's settimeout() function to run an ajax request to your server at a set interval in which you send the id of the last record on the page. The use Javascripts window.location.reload() function to reset the page if the last record's id is different.
Why you don't want to refresh the page
This is bad user experience. You don't want the page refreshing out of no where. The best idea is to send the latest id on the current page to the server and check for any new ids. If there are new ideas send the records back via json and append them to the end of your results table.
This scenario is some complex but possible solution of your requirement!
In our scenario we have developed a sms-gateway and defining a trigger when ever any record is inserted we call a function that sends a sms to our gate way that behind that gateway we have developed our page. :)
In other way by defining timing ajax or many other ways where some what how our some resources are used, we have to compromise.
Ideally you want to trigger an update of data on the page via AJAX as opposed to a full page refresh. You can potentially accomplish this using web sockets. A popular server-side implementation is socket.io. Which uses the nodejs environment.
You could potentially write a MySQL UDF which executes in your trigger and signals nodejs to push more data (which may require writing a nodejs package as well). So, not trivial, but definitely doable :)

mybb - how to check for new private messages

I'm trying to build an chrome app/extension for my website which is mostly a mybb forum. I am wondering if anybody knows how would I check to see if a user has new Pm's or maybe new posts on his thread? Maybe by JS, AJAX, or PHP
As far as events go, generally for PM's there is a field in the database called 'read', which is false if they haven't opened it, and true if they have. On a page load, check to see if there are any messages to the user that are 'unread', and if so, load them, and use JQuery to make a pop up saying a short description of them. You could also have a small AJAX script periodically check for this.
As far as new posts go, the traditional way that I've seen it done (but by no means the best way) is to keep a timestamp of when a user last visited the site. On page load, get every new post/topic that was created after that timestamp, then serialize this data and store it in the database, or in a cookie (if this serialized data already exists, unserialize it, merge the two and reserialize it). If a user visits a topic, get all data from the serialized entry that matches (IE, in the same topic, or the post number) and remove it from the serialized data. Then again on page load or by using an AJAX script, check periodically if they have an 'unread' post on a topic that belong to them (IE, created after their last timestamp value), and use a bit of JQuery to notify them.
Learn JQuery. It is a very friendly javascript framework and you will be up and running in no time. Coding in JQuery is fun!
Do periodic AJAX request.
inject data into DOM or maybe if you are creating a Google Chrome Extension like your tag is telling use the awesome Desktop Notifications System.

Record User Actions Using PHP and Javascript

I am developing an online learning system (PHP, MySQL and Javascript). I would like to track what pages and how long each users spent on each page. Ideally, I would like to record this in a MySQL database. My question is 2 fold:
1. What kind of fields would I include in my db table to record multiple pages accessed?
2. Is this problem best approached by server side only or by using javascript ? e.g. server side: hidden form fields with a page id attached, page id is passed to db and recorded?or Javascript: record all actions in Javascript variables and somehow pass to db at end of session?
Really I am just looking for some high level guidance on an approach as opposed to code snippets.
GF
PHP isn't my normal language, but I would think about creating a module of code that can be called from the top of each of your scripts, that basically logs away "I served this page, with these form variables, at xxx ... ". To be more precise, I would record that in a table.
If you need to know when the user left your page, for a page on another site or perhaps shut down their browser for instance, then a purely server side solution isn't going to cut the mustard. In that event, you are going to have to start thinking about JavaScript, and intercepting events - such as the onUnload event...
Have a read here...
While I know of no solution that can track individual users out of the box (I'm sure there are some), I am pretty sure you could customize Piwik to do this. Piwik aims to be a self-hostable alternative to Google Analytics. It is open source and build on Zend Framework and MySql.
Piwik collects usage statistics through a JavaScript tracking code and a Webbug image for fallback. Basically, what you would need to do is pass the logged in user's user id to the tracking script and then write a plugin that knows how to handle this information.

Categories