How do I update a row in MySQL using php? - php

How do I update the row $pageviews by +1 each time someone visits my page. The table name is news and the row to be updated is $pageviews whose default value is +1. Should I use the update function? And how do I implement it? Below is my code. Can you show a demonstration using these data?
$data = mysql_query("SELECT * FROM news") or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$id = $info['id'];
$pageviews = $info['pageviews'];
}

All you want to do is to increment pageviews value each time that page renders. All you need for that:
1) Get the current value
2) Run UPDATE query updating current value + 1
To do so, you can write a function that would look like as,
function inc_page_views($id) {
$res = mysql_query(sprintf("SELECT * FROM `news` WHERE `id` ='%s'", mysql_real_escape_string($id)));
$data = mysql_fetch_array($res);
// Target view count
$target = $data['pageviews'];
$query = sprintf("UPDATE `news` SET `pageviews` = '%s' WHERE `id` ='%s'", $target + 1, $id);
return mysql_unbuffered_query($query);
}
And then, when rendering a page, you can simply call inc_page_views(..here page id..) and it will do the rest

use this query
mysql_query("Update news SET pageviews = pageviews + 1 ");
or
store the current page id in $current_page_id.
mysql_query("Update news SET pageviews = pageviews + 1 where id = '$current_page_id' ");

Related

php and mySQL database concurrency update

Lets say I wanted to increment a counter in a database every time someone visits a webpage.
The database called 'example' looks like this:
|Name.....| Value..........| id |
===================
|count......| 5................| 1 | <---- 1st row
and the code on the webpage looks like this:
$db = mysqli_connect("localhost", ....);
$q = "SELECT Value FROM example WHERE id = '1'";
$r=mysqli_query($db, $q);
$result = mysqli_fetch_array($r);
$increment = $result[0] + 1;
$q = "UPDATE example SET Value = '$increment' WHERE id = '1'";
mysqli_query($db,$q);
If two people access the webpage at the same time, person A will fetch the value of 5 and immediately after that, person B will fetch the same value. They will both increment it to six and both perform the update one after the other entering 6 as the counter value when it should really be 7 since two people visited the page. How can I prevent this?
you can do it in one statement:
"UPDATE example SET Value = Value + 1 WHERE id = '1'";
so also no other task can change it between your read and update.
Here your script
$db = mysqli_connect("localhost", ....);
$q = "UPDATE example SET Value = Value + 1 WHERE id = '1'";
mysqli_query($db,$q);

How to run query until one record is found?

This is what i am trying right now but no luck
$bid = $next - 2;//This subtracts 2 from the number, this number is also auto generated
$preid = $bid;
$query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$query) or die(mysqli_error($conn));
while(mysqli_num_rows($sql) !=0) {
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
--$preid;
}
whats suppose to happen is that if a record does not exist it subtracts 1 from preid and runs the query again with the new preid and keeps happening until a record it found but cant figure out how to do it.
I am assuming that you are constantly checking database for new values. However, on a large scale application thi is an highly inefficient way to constantly ping the database.
You have made a variable $preid but you are not using it anywhere.
This is how i would do it if i were to go according to your way
$bid = $next - 2;//This subtracts 2 from the number, this number is also auto generated
$preid = $bid;
$query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$query) or die(mysqli_error($conn));
while(mysqli_num_rows($sql) !=0 || !$preid) { //notice here i added the condition for preid.
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
--$preid;
}
now what happens is that the loop will run as long as either of the two condition stays true ie either a row is returned from the database or it will keep searching until preid is not 0.
If you want to test for an empty set, your while should run while mysqli_num_rows == 0
while(mysqli_num_rows($sql) == 0) {
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
$preid--;
}
As #DarkBee has mentionend in his comment, this code is highly vulnerable for an infinite loop which will take down your script, as soon as there are no entries for anything.

PHP MYSQL Next and Previous Product Buttons

I have a dynamic page that pulls the categories from the database. this page is categories.php?CTGID=####, CTGID standing for the category number. Each product then has an ID assigned to it.
When they click on the product within the category it goes to a page Products.php?ID=###. What I want to create is when they are within the Product page there is a next and previous button.
What I would essentially need it to do is get the CTGID of the current product ID then the next button would be the ID of the next product withing that Category ID.
<?php
$db=mysql_connect ("localhost",[username],[password]) or die(mysql_error());
mysql_select_db("rentals");
$rentID = $_GET['ID'];
//Strip html
$strip_ID = strip_tags($rentID);
$html = htmlentities($strip_ID, ENT_QUOTES);
$escape = addslashes($html);
$table="online_rental_db";
$sql = "SELECT * FROM $table WHERE ID=$escape";
$query = mysql_query($sql) or die(mysql_error());
$rentals = mysql_fetch_assoc($query);
$description = ucwords(strtolower($rentals['Description']));
$image = $rentals['Image'];
$download = $rentals['PDF'];
$ID = $rentals['ID'];
$CTGID = $rentals['CTGID'];
$category = $rentals['Category'];
$video = $rentals['Video'];
$bytes = filesize("rentals/".$download);
$model = $rentals['Model'];
$made = ucwords(strtolower($rentals['Manufacturer']));
$productnum = $rentals['Productnum'];
then on the page I just echo out what I need in what area. I have read some articles on the next and previous buttons, but decided I might need some extra advice!
Not sure what you've tried, but in the past I've implemented getting next/previous values from the DB with the following queries:
$curId = 42; // current product id
$curCat = 1; // current category
$sqlPrev = 'SELECT `id` FROM `table`
WHERE `id` < '$curId' AND `catId` = '$curCat'
ORDER BY `id` DESC LIMIT 1;
$sqlNext = 'SELECT `id` FROM `table`
WHERE `id` > '$curId' AND `catId` = '$curCat'
ORDER BY `id` ASC LIMIT 1;
// execute each query
If you get no result back from one of the two queries, it means you are on the first or last item in that category so there is no prev/next button in that case.
Hope that helps.

Can't get SQL Update to work using PHP

I'm trying to get php to update a MySQL table using UPDATE statement but it simply won't work. Here's the code I wrote:
$add = "1";
$counter=mysql_query("SELECT * FROM frases WHERE id = '".$id."'");
while ($ntcounter=mysql_fetch_array($counter)) {
mysql_query("UPDATE frases SET count = '".$ntcounter[count]+$add."' WHERE id = '".$id);
}
As you can see, I am basically trying to update the SQL record to keep track of how many times a specific content ID was visited.
Thanks!
Use an alias in your SQL query (It is not mandatory, but it makes the query much more readable.)
SELECT * as count FROM frases WHERE id = '".$id."'"
And you can now access to your variable
$ntcounter['count']
So the result :
$add = "1";
$id = (int)$id
$counter = mysql_query("SELECT * as count FROM frases WHERE id = '".$id."'");
while ($ntcounter = mysql_fetch_assoc($counter)) {
mysql_query("UPDATE frases SET count = '".($ntcounter['count']+$add)."' WHERE id = '".$id);
}
You don't really need two queries. You should just be able to update like this
mysql_query("UPDATE frases SET `count` = `count` + 1 WHERE id = ".$id);
You didn't close the single quote at the end of the update statement:
mysql_query("UPDATE frases SET count = '".$ntcounter[count]+$add."' WHERE id = '".$id."'")

Php/MySQL help - random daily pick?

I'm trying to get a pick from my DB that would last for a day (daily pick). I use the following code:
$query = 'SELECT * FROM table ORDER BY rand() LIMIT 1
But as you can see it only gives me a random pick from the table, and every time I refresh the page it gets me a new random pick. How can I make the pick to last for a whole day?
Thanks in advance <3
I'm trying this:
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
But I get the following error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource. This is the part that gets broken:
$results = mysql_query($query);
while($line = mysql_fetch_assoc($results))
So... it should look like this, right? (I mean, choosing the daily random pick?)
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
I'm trying this now:
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
However, it gets me a mistake that I'm using the 'has' function on a non-object.
If you set the SEED for the rand to an integer value that changes daily, that would solve your problem
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
Would do the trick.
A sane means of doing this would be to automatically generate the pick of the day content via a cron job that was setup to run once a day.
As such, the cron job would execute the SQL you provided and store the appropriate content in a flat file/database table, etc. (or perhaps even just store the choosen id in another table for future lookup purposes).
You can try something like this:
$total = 'SELECT COUNT(*) FROM table;';
$query = 'SELECT * FROM table ORDER BY id ASC LIMIT 1 OFFSET ' . (date('Ymd') % $total) . ';';
I think you'll need to update the random picked record with "today" field = 1..
Something like this:
// ------------
// Run this 3 commands once a day
// Reset all records
mysql_query("UPDATE `table` SET `today` = 0");
// Pick one
$sql = mysql_query("SELECT `id` FROM `table` ORDER BY RAND() LIMIT 1");
$id = mysql_result($sql, 0, 'id');
// Update the record
mysql_query("UPDATE `table` SET `today` = 1 WHERE `id` = {$id}");
// ------------
// Now you can find again your "random found record":
$query = mysql_query("SELECT * FROM `table` WHERE `today` = 1");

Categories