PHP + 1 really adds two - php

Currently, I have the following PHP code loaded every time the page is refreshed. I am trying to update the views column +1 every time the page is loaded. To do this, I first retrive the previous views value from the table, then run another query to add + to that number. The problem that is occurring is every time I refresh the page, The code somehow adds two instead of 1. So instead of the $viewsA variable increasing by +1, it is increasing by +2.
$query = mysql_query("SELECT * FROM Games WHERE pagename = '$game' ");
WHILE($datarows = mysql_fetch_array($query)):
$title = $datarows['title'];
$description = $datarows['desc'];
$img_url = $datarows['img'];
$cat = $datarows['cat'];
$pagename = $datarows['page'];
$rating = $datarows['rat'];
$viewsA = $datarows['view_count'];
$gameid = $datarows['id'];
endwhile;
$updateviews = $viewsA +1;
mysql_query("UPDATE `trainw_games`.`Games` SET `view_count` = '$updateviews' WHERE `Games`.`id` = $gameid;");
What do I need to change to make it only add +1 to the views column?

I don't think that a while loop is appropriate for this problem. I would recommend to echo $viewsA . '-' . $updateviews; to see what the value is before and after the add.
But, why not just run a single UPDATE statement?
UPDATE Games SET view_count = view_count + 1 WHERE Games.id = $gameid
Of course, you should stop using mysql_ functions and use either MySQLi or PDO:
$stmt = $mysqli->prepare("UPDATE Games SET view_count = view_count + 1 WHERE Games.id = ?");
$stmt->bind_param($gameid);
$stmt->execute();
$stmt->close();

Do you have multiple rows in your database? If yes, it maybe caused by overriding the previous value.
For example:-
If first row the view_count is 1.
While the second row view_count is 2.
that overrides the the first row with 2 + 1 = 3
Which makes you thought increased by 2?
UPDATE 1:
Ok, try this, put this
$updateviews1 = $viewsA + 1;
if ($viewsA < $updateviews1) { //execute the viewsA + 1 }

Related

Update multiple rows for 1000 records in one go

I have one table based on which one I have to update 6 rows in the other table for matching ids. It is total of over 1000 records so most of the time I get timeout error with current script.
The way I do it now is, I select the range of ids between two dates from the first table, store it into an array and then run foreach loop making update in the second table where the ids are the same, so basically I run a query for every single id.
Is there anyway I could speed it up the process?
I found only a way to generate the each within the foreach loop
UPDATE product SET price = CASE
WHEN ID = $ID1 THEN $price1
WHEN ID = $ID1 THEN $price2
END
But I don't know how could I modify this to update multiple rows at the same time not just one.
My script code look like that
$sql = "SELECT * FROM `games` where (ev_tstamp >= '".$timestamp1."' and ev_tstamp <= '".$timestamp2."')";
while($row = mysqli_fetch_array($sql1)){
$one_of =[
"fix_id" =>$row['fix_id'],
"t1_res" =>$row['t1_res'],
"t2_res" =>$row['t2_res'],
"ht_res_t1" =>$row['ht_res_t1'],
"ht_res_t2" =>$row['ht_res_t2'],
"y_card_t1" =>$row['y_card_t1'],
"y_card_t2" =>$row['y_card_t2'],
"t1_corners" =>$row['t1_corners'],
"t2_corners" =>$row['t2_corners'],
"red_card_t1" =>$row['red_card_t1'],
"red_card_t2" =>$row['red_card_t2']
];
array_push($today_games,$one_of);
}
foreach($today_games as $key=>$val){
$cards_t1=$val['red_card_t1']+$val['y_card_t1'];
$cards_t2=$val['red_card_t2']+$val['y_card_t2'];
$sql = "Update sights SET t1_res='".$val['t1_res']."',
t2_res='".$val['t2_res']."', ev_tstamp='".$val['ev_tstamp']."',
ht_res_t1='".$val['ht_res_t1']."', ht_res_t2='".$val['ht_res_t2']."',
t1_corners='".$val['t1_corners']."',t2_corners='".$val['t2_corners']."',
t1_cards='".$cards_t1."',t2_cards='".$cards_t2."'
where fix_id='".$val['fix_id']."' "
}
Consider an UPDATE...JOIN query using fix_id as join column. Below runs mysqli parameterized query using timestamps. No loop needed.
$sql = "UPDATE sights s
INNER JOIN `games` g
ON s.fix_id = g.fix_id
AND g.ev_tstamp >= ? and g.ev_tstamp <= ?
SET s.t1_res. = g.t1_res,
s.t2_res. = g.t2_res,
s.ev_tstamp = g.ev_tstamp,
s.ht_res_t1 = g.ht_res_t1,
s.ht_res_t2 = g.ht_res_t2,
s.t1_corners = g.t1_corners,
s.t2_corners = g.t2_corners,
s.t1_cards = (g.red_card_t1 + g.y_card_t1),
s.t2_cards = (g.red_card_t2 + g.y_card_t2)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $timestamp1, $timestamp2);
mysqli_stmt_execute($stmt);

PHP PDO pagination foreach

I'm trying to create a pagination for my PDO query. I cant figure it out. I've tried numerous google searches, but nothing that will work for me. [I probably didn't search hard enough. I'm not sure]
This is my code:
$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$nodes2= $stm2->fetchAll();
foreach ($nodes2 as $n1) {
echo "text";
}
I want to be able to limit 10 comments per page, and use $_GET['PAGE'] for the page.
Something that I tried
$sql2 = "SELECT * FROM comments WHERE shown = '1'ORDER BY ID DESC";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$nodes2= $stm2->fetchAll();
$page_of_pagination = 1;
$chunked = array_chunk($nodes2->get_items(), 10);
foreach ($chunked[$page_of_pagination] as $n1) {
echo "text";
}
If someone could help out, I appreciate it.
You need to limit the query that you are performing, getting all values from the database and then limiting the result to what you want is a bad design choice because it's highly inefficient.
You need to do this:
$page = (int)$_GET['PAGE']; // to prevent injection attacks or other issues
$rowsPerPage = 10;
$startLimit = ($page - 1) * $rowsPerPage; // -1 because you need to start from 0
$sql2 = "SELECT * FROM comments WHERE shown = '1' ORDER BY ID DESC LIMIT {$startLimit}, {$rowsPerPage}";
What LIMIT does:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants
More information here: http://dev.mysql.com/doc/refman/5.7/en/select.html
Then you can proceed getting the result and showing it.
Edit after comment:
To get all the pages for display you need to know how many pages are there so you need to do a count on that SELECT statement using the same filters, meaning:
SELECT COUNT(*) as count FROM comments WHERE shown = '1'
Store this count in a variable. To get the number of pages you divide the count by the number of rows per page you want to display and round up:
$totalNumberOfPages = ceil($count / $rowsPerPage);
and to display them:
foreach(range(1, $totalNumberOfPages) as $pageNumber) {
echo '' . $pageNumber . '';
}

Incorrectly sum in a while loop

$dt = mysql_query("SELECT * FROM `member_territory` mt LEFT JOIN `drug_territory` dt ON mt.mt_ter = dt.t_id");
while($t = mysql_fetch_array($dt)) {
$total +=($t['t_reward']* $t['mt_lev'])*150;
mysql_query("UPDATE `members` SET
`drug_income` = '".$total."',
`drug_incometotal` = `drug_incometotal` + '".$total."',
`wallet` = `wallet` + '".$total."'
WHERE `playerid` = '".$t['mt_playerid']."'");
}
So here is my code rather self explainingtary $total when inserted into drug_income that is correct but when ever it is inserted into drug_incometotal or wallet its incorrect.
im not sure why and i have tried everything to my knowledge to pull my head around it!!.
Any ideas why i am getting this incorrect result ( as i say drug_income is correct) only when i try to '+' it to something in the data base it returns an incorrect result.
i dont want to increment just once after the loop... – user3740302 1 min ago
Okay then. So you should probably move your UPDATE query outside of the loop, right?
You may try this modified update query
mysql_query("UPDATE `members` SET drug_income = ".$total.", drug_incometotal = drug_incometotal + ".$total.", wallet = wallet + ".$total." WHERE `playerid` = '".$t['mt_playerid']."'");
It may resolve your problem..

Get value and increment by one for each user

I have this script as a cron job set to run every 5 mins, the problem is it will not increment the energy level as I believe it should. If anyone can tell me what I am doing wrong here it would be great.
Remember, this returns no errors, just doesn't work, also the database connect info is all correct, just left out of the post.
{
$energy = mysql_query("SELECT energy FROM members WHERE id=$id");
//get current users energy level
$energy_max = mysql_query("SELECT energy-Max FROM members WHERE id=$id");
//get current users Maximum energy level
if ($energy < $energy_max)
// do -if current energy level is less than maximum
{
$energy = $energy ++;
//increment energy by 1
mysql_query("UPDATE members SET energy= $energy");
//set the new energy level
}
$id++;
//increment to the next user
}
You can solve everything within a single statement
UPDATE `members` SET `energy` = `energy` + 1 WHERE `energy-Max` > `energy`;
This way you have one instead of 3 * number-of-members queries
You forgot the WHERE id = $id in the update Statement.
mysql_query("UPDATE members SET energy= $energy WHERE id = $id");
But KingCrunch's answer is better ..
mysql_query doesn't return values, only so-called query id. You have to fetch actual data:
$query = mysql_query("SELECT energy FROM members WHERE id=$id");
$val = mysql_fetch_assoc($query); // Now the data is in $val['energy']
Of course you can do this quicker, via this (as pointed in other answer):
UPDATE members SET energy = energy + 1 WHERE energy < energy-Max;

How to build next and previous links with php?

I use this code to get the informations about a certain id
$sql = dbquery("SELECT * FROM `videos` WHERE `id` = ".$local_id." ");
while($row = mysql_fetch_array($sql)){
$video_id = $row["id"];
$video_title = $row["title"];
}
Let's say the link of a page would be example.com/video.php?id=34
How can i get the next and previous $video_id and $video_title depending on the current id?
A problem is that i can't increase or decrease the value of the current id by 1 because the 35 or 33 may be deleted in the meanwhile...
How can i achieve this?
//edit
I have a very big problem: the previous link sends me to the right link but the next link always sends me to the last video added in the database.
If i go to the last or first videos added in the database i get an error because there are no more next and previous videos added.
Perhaps two more queries would work ...
select id,title from videos where id < $local_id order by id desc limit 1
select id,title from videos where id > $local_id order by id asc limit 1
You have to use select and limit to get that one row you want, i.e.,
SELECT * FROM `videos` WHERE `id` < " . $local_id . " ORDER BY `id` DESC LIMIT 1
Or use > and ORDER BYidASC for the next video, instead of the previous I showed above.
Here you go through
// entry per page
$rowsPerPage = 3;
// Set page number
if(isset($_GET['page']))
$pageNum = $_GET['page'];
else
$pageNum = 1;
Note: Following code is use to show/set next & previous page number.
Note: If the current page is homepage then default $pageNum is 1 and
if $pageNum is set as 2, it will work as
if($pageNum){
$PreviousPageNumber = $pageNum - 1;
$NextPageNumber = $pageNum + 1;
echo '<a href="?page='. $PreviousPageNumber .'>Previous Page</a>';
echo '<a href="?page='. $NextPageNumber .'>Next Page</a>";
}
Note: Following code is use to show record affected by page numbers
$GetPreviousRecord = ($pageNum - 1) * $rowsPerPage;
Note: The first, optional value of LIMIT is the start position. Note:
And the second required value is the number of rows to retrieve.
$query = "SELECT * FROM post WHERE LIMIT $GetPreviousRecord, $rowsPerPage";
$result = mysql_query($query);
And in last use the WHILE loop to get all records from database by using LIMIT.

Categories