Taking a value from a mysql table and adding 1 - php

This is my first time posting in stackoverflow so please tell me if I need to add more information!
I am attempting to take a value from the mysql database and add 1 to it when the page loads. The user clicks on the link on the first page and when the linked page is loading and the php code below runs it adds 1 to the value of the column Clickcount in the entry with the Name value TheButton in the table "lots".
The following code worked when I ran it through Dreamweaver with WAMP:
<?php
$con=mysqli_connect("localhost","root","qwerty71","Lots");
mysqli_query($con,"UPDATE Lots SET Clickcount=Clickcount+1
WHERE Name='TheButton'");
$result=mysqli_query($con,"SELECT * FROM Lots where Name='TheButton'");
while($row= mysqli_fetch_array($result))
{
echo $row['Clickcount'];
}
mysqli_close($con);
?>
But when I put the same code into my website (only changing the values after the mysqli_connect to connect to the database) it doesn't work. The echo at the bottom is to show the value after it is changed, I have the same echo on the first page to show the value before it is edited by the second page. I set the value to zero in the database before I loaded the first page or clicked the link. The first page shows the value at zero, and after clicking the link the second page changes the value and displays a 1. When I try to click back to the first page it shows a 1 instead of a zero, but then both pages continue to display 1s instead of adding 1 every time the link is clicked.
I have tried multiple ways of changing the code after the SET Clickcount=
Including attempting to add a variable before query that I set equal to the Clickcount value and trying to add 1 to that.
Is there an error in my code that would prevent it from working properly, or is there an alternate way to set this up to get the desired result?
Re-explanation for clarity:
My table is as follows:
Name Clickcount
TheButton 0
I am trying to increase the value under "clickcount" by 1 every time a page is loaded. My code (posted above) functioned properly when run on a local server, I changed the parameters to match my server online.
The homepage has a portion of the code above to show the value of the Clickcount column and a link to the second page, where the code above is located.
The code functioned once, changing the value from zero to one, but then ceased to work on consecutive attempts.
Is there an error in my code? Or is there a better way to accomplish the task of increasing the value?
Further update:
The code seems to be working once every 5-10 minutes. I have left it as it is above, and it was not doing this before. I do not know what changed.
In addition, every few times that it does work, I get the result of receiving two different values when calling the following portion of the code on two separate pages:
$result=mysqli_query($con,"SELECT * FROM Lots where Name='TheButton'");
while($row= mysqli_fetch_array($result))
{
echo $row['Clickcount'];
}
mysqli_close($con);
This code is on the homepage, where it sometimes results in a number one less than what the value is recorded to be in the mysql table. Where on the page with the complete code listed above, it always shows the same value as in the table.
In my continuing effort to figure this out, I have removed all of the files off of the server where my site is hosted, and started again from scratch. After re-writing all of the code for the two pages, creating a new table in a new database, and implementing the code above on the second page, the error remains.
I have also just now signed up for a new hosting service to see if it was the server that was causing the problem. Sadly, that was not it. Does anyone have a suggestion for a solution?

Look to this points:
Copy your query and put in the database. It works?
In the end of your update line, put or die(mysqli_error($con)). If show errors, look to error;
There value 'TheButton' in the column Name in your remote table?
Try change in the clause where in update query, Name='TheButton' to Name LIKE 'TheButton'
Always throw messages errors in your codes. Is the best way to find mistakes. ;)

The page was loading a cached version instead of loading from the site itself. I added some coding to the header to remove the caching, this fixed the problem.

Related

Echo new row when it got added to database

I am trying for a few days now to figure out how I can do this.
I have two pages, one is index.php, other is add.php .
1)Index.php - I want it do display last 5 rows from database table.
2)Add.php - contains form which adds new row to database.
How can I update values that are shown on index.php when I add new row?
So lets say I have index.php already opened on one tab, and on other one is Add.php. When I fill the form on add.php,
I want it to automatically notifies index.php that there is a new row,and that it should change values without refreshing the index.php tab.
Do I need VPS for this?What is the best way to do this theoretically?
There is no need in setting up a VPS for this. A VPS is Just a server in which u can install your own software. You are already using a server for PHP (local perhaps).
U can create a websocket server. Once you add a row you send a message tot the websocket server which will then tell the index page to resfresh.
Previous option is a lot of work for a rather simple functionaliteit. I'd suggest the simplest option as recommended by FrankerZ. Only if you refresh the page at a set interval using JavaScript (window.setInterval) then the page would keep refreshing. I don' t think that's ideal. You van however send a xhtmlhttprequest to store the contents for the index page and run that request every x seconds. Then u can compare the 2 contents and decide if the page should be refreshed or not.

AJAX / PHP voting system: Content not updating on first click

TESTING ENVIRONMENT: Windows 8 using the tool XAMMP. PHP and Mysql are up to date.
MY KNOWLEDGE: Starter.
QUESTION: I can't get the updated content immediately after the first click, only after the second, which can become pretty nasty considering I have two kind of buttons for my little voting system. Yes, I said a lot not alot : )
What is the cause for this predicament and how can I fix this?
WHAT I TRIED: Checked my developer tools network analysis and I get a status 200 with the correct value for every click. When using my firefox DOM inspector view I saw something unusual: upon the first click only #votes is marked in orange probably denoting that it has been affected. However, only on the second attempt on the same button both divs, #votes and #progress, get marked orange in addition with the updated values. So I expect it does on second click but not on the first one. Then I refreshed my page and tried something else. I clicked on "bad" and this time the second click landed on "good" with bad updating the value in the DOM. It seems as if the entire process is split and does not happen simultaneously which is why I speculate that:
Click 1: Sends data to php.
Click 2: Gets the data from php and displays it on the DOM.
The PHP code itself in conjunction with my database and HTML (if set to submit) works perfectly fine so I dont assume there is anything wrong on the server side. Connection to the database is set. My sessions work perfectly. No errors.
My console shows 0 javascript errors.
Test 1 : I commented out my entire php code and set up a testing variable with a simple string and changed the values in my code below accordingly. To my suprise, on clicking it immediately took the data and display the content of my testing variable.
Test 2 :: I removed the php codes from the two div tags which you will see below. They act as placeholders that show the current value before any AJAX happens. I removed those and I get an update on first click as the container was first empty. Although, on second click and toggling between good and bad happened to be a mess again.
Test 2 :: Placing jquery and my AJAX script in the head of the document did not do the job either (just to be on the safe side). Prior it was before the </body> tag
I access the returned json object through my callback parameter named data which then inserts html and css via jquery into the respective div containers.
Converted the jquery below to pure javascript but no positive change could be observed.
JAVASCRIPT / AJAX
function vote(type) {
$.get('php/core/voting_system_function.php', {vote:type}, function(data) {
$('#votes').html(data.votes_sum);
$('#progress').css('width', data.progress);
}, 'json');
}
HTML
The buttons onclick event feeds the data on to the parameter within my vote functions which then sends it to {vote:type} and then to my php file. This allows me to do several checks to see if the click was either 'good' or 'bad' and substract or add data accordingly in my database.
#votes and #progress
<div id="quality_meter">
<div id="progress" style="width:<?php echo $progress ?>"></div>
</div>
<div id='votes'><?php echo $votes_sum ?></div>
The connection to the database is correct and readable through a require.
The script works assuming the user actually logged in as they cant access the page otherwise. As you can see I am making use of two session variables.
As you can see, I am making checks to see which button has been clicked and query accordingly.
The last bit of the code returns a json object through an associative array with the data stored by the variables you see there which is votes_sum and progress. I use json_encode to return the json representation of my value.
When you say you're not getting the response until the second click, do you mean the "votes_sum" in the votes div isn't updating with the latest votes?
The reason for this is that you calculate the $votes_sum value before you call the voting_system() function which is what updates the votes count, then after voting_system() you move the $votes_sum - unchanged - to the $output array.

WordPress - Update Database Value in real time.

I have a piece of code that counts the lines of code within a wordpress site. I have successfully managed to send that number to the wordpress database so I can call on it in a different location in my theme files (this is because the script needs to be in the root of the install to count the lines of code).
Whilst this works really nicely, the BIG issue I have is that the number won't update itself automatically. i.e. the code for counting lines is www.mysite.com/loc.php and I mus go to this page and let it load before it updates the value in the database.
Is there a way to make it so that the value just automatically updates, so I don't have to navigate to the page for this to happen? i.e. when I add more lines of code, the value in the database updates itself.
Code for sending value to the db is as follows:
$num_of_lines = $folder -> count_lines();
update_option('line_count', $num_of_lines);
look into jquery and ajax call
Wordpress provides for you the framework to call backend functions on the frontend
http://wptheming.com/2013/07/simple-ajax-example/
another example:
http://premium.wpmudev.org/blog/how-to-use-ajax-with-php-on-your-wp-site-without-a-plugin/
You need to create a trigger, in order to update automatically MYSQL database
Look at this, i hope it will help
How to automatically update a MYSQL column value using formula and data from other columns in same row?

PHP Session variable changing from page to page

I'm using a session variable to save the last page the user visited in the search results so that they can go back to that page.
if I make
echo($_SESSION['page'])
at he end of the results pages the value is correct, but when I reload the page (or load any other page) the value is increased by 1. I made a echo($_SESSION['page']) right after the session_start() call and it was already increased, so I guess it's been increased right before the PHP code for the search results finishes running but can't find the line of code that is doing so.
In order to test this added a new variable called $_SESSION['page2'] and this new variable is been increased too.
Any ideas?
EDIT
The variable is taking the value from a Pager object like this
$_SESSION['page'] = $pager->getCurrentPageID();
And I can't find any other place where its been set to a different value. We use the same unit and code in a different site and never had this problem before. Tried replacing the code and the Pager class definition with those from the other site and that didn't fix it.
session_start();
Has to be called before anything is echoed to the browser, best practice is to have it as the first thing you have on your PHP page.
Giving you a better answers is no problem, if you provide more code.
More about session_start();

Browser goes Back after PHP page is executed

I have a form which sends data to a proccess page. Is it possible when the code in the process page is executed for the browser to jump back to the previous page?
EDIT
The reason i want this, is because i have a set of parameters which contains checkboxes. These parameters are echoed out via a while loop. I have a table where it shows which of those parameters are active. I would like to check the checkboxes by defualt where the corresponding parameter is in the table.
|||||||||||||||||||||||||||||||| Example ||||||||||||||||||||||||||||||
PARAMETERS:
T-Shirt: checked
Distance: checked
Race: unchecked
TABLE (parameters)
• T-Shirt
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||the example above checks the box if it already exists in the parameters table. When the user clicks back after the process page, the boxes he selected is checked.
Hope i am clear enough
Regards
I think a nice solution might be to implement a front controller for your webbage, a central script to include the appropirate page. Using a system like that, the user stays on the same page all the time even when other pages are loaded.
I haven't used a front controller in quite some time, so I won't write examples due to potential errors and poor coding. You can probably find some examples using google though, I wouldn't be surprised if the subject has been brought up here on Stackoverflow before either.
Even though I'll have to point out Griffin's solution is the best, if you're dead set on a redirect, simply have your PHP script execute the following lines:
echo '<script>document.history.go(-1);</script>';
die();
Or even
die('<script>document.history.go(-1);</script>');
It's a dirty solution, so I must advise against it.

Categories