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;
Related
main function that run every 3 sec and update value in db
function 1
public function set_cron_value() {
for($i=1; $i < 20; $i++) {
$this->db->query('UPDATE users SET pass_change_flag = (pass_change_flag + 1) WHERE u_id = 123');
sleep(3);
}
}
this function return the db data
function 2
public function get_cron_value() {
echo $this->db->query('SELECT * FROM users WHERE u_id = 123')->row()->pass_change_flag;
}
when function 1 is running function 2 halt and did't return any thing until function 1 execution completed is there any solution that function 1 execution did not effect other functions execution
i am using php frame work codeigniter
thanks
Try this -
// NOT TESTET, just to show concept.
function Reorder()
{
// query to get all id's, ordered by priority ASC.
$things = mysql_query("SELECT id FROM table ORDER BY priority ASC");
// iterate thru all items, and give each a new priority
$priority = 0;
while($row = mysql_fetch_assoc($things))
{
mysql_query("UPDATE table SET priority = ".$priority." WHERE id = ".$row['id']);
// add 1 to $priority, then the next item will have a higher priority of 1.
$priority++;
}
}
That's for reordering your functions, and then you can just have one function move to the top and one to the bottom :
// NOT TESTET, just to show concept
function MoveToTop($id)
{
// get the priority of the item, and the max priority available
$item = mysql_fetch_assoc(mysql_query("SELECT priority, MAX(priority) AS max_priority FROM table WHERE id = ".$id));
// move all items above the current item, one prioroty down.
mysql_query("UPDATE table SET priority = priority - 1 WHERE priority >= ". $item['priority']);
// set priority of the current item to the max priority
mysql_query("UPDATE table SET priority = ".$item['max_priority']." WHERE id = ".$id);
// Reorder() could be called here, to make absolutely sure everything is in order...
}
// NOT TESTET, just to show concept
function MoveToBottom($id)
{
// get the priority of the item.
$item = mysql_fetch_assoc(mysql_query("SELECT priority FROM table WHERE id = ".$id));
// move all items below the current item, one priority up (to make room)
mysql_query("UPDATE table SET priority = priority + 1 WHERE priority <= ". $item['priority']);
// position the current item at priority 0 (zero)
mysql_query("UPDATE table SET priority = 0 WHERE id = ".$id);
// Reorder() could be called here, to make absolutely sure everything is in order...
}
To run a script with intervals you can schedule a CRON JOB. This will be the best solution for running script after your specified time.
It depends on your server hosting you can schedule mulitple CRON JOBS from cpanel of your website.
I am new to php so far i wrote this referral script:
<?php
ob_start();
include( $_SERVER['DOCUMENT_ROOT'] . '/config.php' );
mysql_connect(DB_HOST,DB_USER,DB_PASS);
mysql_select_db(DB_NAME);
$id = $_REQUEST['id'];
$uid = $_REQUEST['uid'];
$oid = $_REQUEST['oid'];
$new = $_REQUEST['new'];
$total = $_REQUEST['total'];
$sig = $_REQUEST['sig'];
// Secrete Key
$hash = 'myapikey';
// Output results
if ($sig == $hash) {
//Users point update query here (it's working )
$users = mysql_query("SELECT points FROM users WHERE id=".$uid);
$rows = mysql_fetch_array($users);
$user_points = $rows['points'];
$query1 = mysql_query("update users set points=($user_points+$new) where id=".$uid );
//Updating referral coins (it's not working )
$query2 = ("SELECT points, referral_id, level FROM users WHERE referral_id=".$uid );
$user_rows = mysql_query($query2);
$all=mysql_fetch_array($user_rows,MYSQL_BOTH);
if($all['referral_id'] != 0 && $all['level'] == 0){
$lvl0 = $new*(15/100);
$referal_points = $lvl0;
$update_referral_points = ("update users set points = points + $referal_points where referral_id = ".$all['referral_id']);
mysql_query($update_referral_points);
} else if($all['referral_id'] != 0 && $all['level'] == 1){
$lvl1 = $new*(25/100);
$referal_points = $lvl1;
$update_referral_points = ("update users set points = points + $referal_points where referral_id = ".$all['referral_id']);
mysql_query($update_referral_points);
}
print "1\n";
} else {
print "0\n";
}
?>
How Script working:
whenever someone signup using referral code i have insert referral code user id into new user referral_id row, & through $_REQUEST['']; my app sending points ($new) to user...
$query1 is working fine there's problem to execute $query2, in short $query2 needs to be fixed; something getting wrong, that i am not able to figure out if any pro can help me out this i will appreciate it...
DB structure:
users table:
id (AI) name points Referral code Referral id Level
=========== ========== ========== ================== ============== ======
1 user A 0 abcdef123 0 0
2 user B 100 bvsuda897 1 1
3 user C 500 vrtasio65 2 0
In this example above,
1- user C signup using user B Referral code = bvsuda897
2- right now user B level is 1 so whenever user C earn point ($new) my app should give user B 25% coins of user C $new
The Problem
right now when my app sending coins to user C, user B not getting coins, because something wrong in query2
After spending some more time looking over your code, I have tracked down your issue. First, you need to get the referral_id from the $users query.
$users = mysql_query("SELECT points, referral_id FROM users WHERE id=".$uid);
Then $query2 needs to match the id to the user's referral_id, not the other way around.
$query2 = "SELECT id, points, referral_id, level FROM users WHERE id=".$rows['referral_id'];
Your UPDATE queries may need some work after that, but this will get you in to the if else conditions.
Successful code determined by OP
//Updating referral coins
$query2 = "SELECT id, points, referral_id, level FROM users WHERE id=".$rows['referral_id']; $user_rows = mysql_query($query2);
$all=mysql_fetch_array($user_rows,MYSQL_BOTH);
$lvl0 = intval((5/100) * $new);
$lvl1 = intval((10/100) * $new);
$query3 = mysql_query("update users set points = (points + $lvl0) where level = 0 AND referral_id = ".$all['referral_id']);
$query4 = mysql_query("update users set points = (points + $lvl1) where level = 1 AND referral_id = ".$all['referral_id']);
Now I appreciate that you are in the learning stage, but I want to point out a couple things that will cause confusions as you pursue PHP programming in the future.
First off, as Option mentioned, the MySQL functions you are using have been deprecated. They do not exist in the current stable version of PHP, and your code will no longer work if the server is updated. Look in to MySQLi or PDO as alternatives. It's a lot to learn, but some Googling will get you some guidance.
Second is your use of $_REQUEST, which combines the values of $_GET, $_POST and $_COOKIE, allowing easy manipulation by visitors. It may be that you are only using it for the user details while testing your other code, but I just want to make sure you know about PHP sessions, which is the better way to store a relationship between a logged in user and their persistent variables.
sorry about the title, i really did not know what I should call it, but hopefully you will be able to aid me with my script.
What I am trying to achieve (with my less than 5 hour total experience with any sort of "programming", hence the horrid coding) is to send one query X times, and then put a new query into those newly created rows.
if(isset($_SESSION['email'])) { // IF LOGGED IN
$sql = mysql_query("SELECT max(ordrenr) FROM antalstabel") or die(mysql_error());
$maxordrenr = mysql_query($sql);
$nextnumber = $maxordrenr + 1;
$maxplusantal = $maxordrenr + $antal;
$antal = count($items); // COUNTS DIFFERENT ITEMS IN CART.
for ($i = $maxordrenr; $i <= $maxplusantal; $i++) {
$sql = mysql_query("INSERT INTO antalstabel (ordrenr) VALUES ('$nextnumber')") or die(mysql_error());
}
}
This is my first query, what this does (or what I want it to do) is to get the max ID of the table "antalstabel" add +1 and then count a certain amount up which is defined as $items untill it has executed X rows.
My first issue here, is the fact that my table consists of two key primaries, so returning a query like this would result in an error since after one return the two rows would be identical and will not execute.
The second issue is the fact that the next value in the table should not be inserted X times after each other, but rather be certain IDs added in afterwards.
What I am trying to achieve ultimately (not only by this script, but this is the current issue) is something like this:
ordrenr(key)varenr(key) antal
1 3 1
1 2 2
2 1 4
3 1 1
3 2 1
3 3 1
Does this make any sense whatsoever for anyone and can anyone tell me whether my method of doing this is jsut hopeless or have some better ideas for me to use as execution for ending up with something like this?
Should I not use primary keys or how does this work?
Thank you for even taking the time to read this :)
-Victor
EDIT for future:
changed script to this for it to work:
if(isset($_SESSION['email'])) { // IF LOGGED IN
$sql = mysql_query("SELECT * FROM antalstabel ORDER BY ordrenr DESC LIMIT 1") or die(mysql_error());
$row = mysql_fetch_assoc($sql);
$maxordrenr = $row['ordrenr'];
$nextnumber = $maxordrenr + 1;
$maxplusantal = $maxordrenr + $antal;
$antal = count($items); // COUNTS DIFFERENT ITEMS IN CART.
for ($i = $maxordrenr; $i <= $maxplusantal; $i++) {
$sql = mysql_query("INSERT INTO antalstabel (ordrenr, varenr) VALUES ('$nextnumber','1236')") or die(mysql_error());
}
$maxordrenr = mysql_query($sql);
should be
$maxordrenr = mysql_result($sql,0);
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 }
I have created a lottery script in php. My problem is now selecting more then one winner. Because it is possible for players to have the same number on their tickets. Here I am supplying the two table structures and the source code.
lotto_game {
id(int)
jackpot(int)
status(varchar10)
pick_1(int)
pick_2(int)
pick_3(int)
pick_4(int)
pick_5(int)
tickets_sold(int)
winner(text)
}
lotto_picks {
lotto_id(int)
user_id(int)
choice_1(int)
choice_2(int)
choice_3(int)
choice_4(int)
choice_5(int)
ticket_status(int)
}
These are my two tables with in my database. For examples sake we will create 2 users with the id's 1, and 2. So what happens is when the script runs it is suppose to change the lotto_game status from 'active' to 'finished' then add the random lottery numbers into each pick_* column.
$one = rand(1,30);
$two = rand(1,30);
$three = rand(1,30);
$four = rand(1,30);
$five = rand(1,30);
mysql_query("UPDATE `lotto_game` SET
pick_1 = '$one',
pick_2 = '$two',
pick_3 = '$three',
pick_4 = '$four',
pick_5 = '$five',
status = 'finished'
WHERE status = 'active'");
That wasn't too hard I will admit. But this is just the beginning of the end.
$lotto['tickets'] = mysql_query("SELECT ticket_id FROM `lotto_picks` WHERE ticket_status='valid'");
#$lotto[winners] = mysql_query("SELECT ticket_id,user_id FROM `lotto_picks` WHERE choice_1 = '$one' AND choice_2 = '$two' AND choice_3 = '$three' AND choice_4 = '$four' AND choice_5 = '$five'");
$lotto['num_tickets'] = mysql_num_rows($lotto['tickets']);
#$lotto[winner_id] = mysql_fetch_array(#$lotto[winners]);
$lotto['jackpot'] = mysql_query("SELECT jackpot FROM `lotto_game` WHERE status='active'");
$lotto['winner_jackpot'] = mysql_fetch_array($lotto['jackpot']);
$lotto['num_winners'] = mysql_num_rows($lotto['winners']);
//echo #$lotto['num_tickets'];
//echo #$lotto['num_winners'];
$winner = $lotto['num_winners'];
//echo #$lotto['winner_id']['user_id'];
$jackpot = $lotto['winner_jackpot']['jackpot'];
$id = #$lotto[winner_id][user_id];
if ($winner == 1) {
mysql_query("UPDATE `character` SET
decivers = decivers +'$jackpot'
WHERE user_id='$id'");
}
This is what I have come up with and it really seems to work with one winner. But I just cant figure out where to go from here. I have tried using some arrays but nothing works. I know what needs to be done but can't figure out how to do it.
When I search for winners I need to put into an array all their user id's.
so extra decivers is money, if anyone is confused on that. The status on the tickets doesn't really matter here but if you must know it just determines if the ticket_status is 'valid' or 'invalid'
i think you've chosen the wrong storage formats for your picked numbers. The standard approach is to use binary values which have N-th bit set if the number N is choosen.
Consider this example: user chooses numbers "2 4 5 9 11". Setting corresponding bits to 1 gives '10100011010' which is decimal 1306. Now the lottery picks "4 7 9 12 13" which is '1100101001000' == 6472. Perform a bitwise AND on both values and count the number of bits set in the result:
SELECT BIT_COUNT(1306 & 6472)
this immediately tells us that the user has 2 correct picks. Just as easy you can select "full" winners:
SELECT * FROM tickets WHERE BIT_COUNT(tickets.pick & lotto.pick) = 5
or sort the tickets by the number of correct picks
SELECT * FROM tickets ORDER BY BIT_COUNT(tickets.pick & lotto.pick) DESC
$winners_array = array();
if(mysql_num_rows($lotto['winners'])!=0){
while($row =mysql_fetch_array($lotto['winners'])){
if(!in_array($row['user_id'],$winners)) $winners[] = $row['user_id'];
}
}
$winners will be an array with all the winners user_ids