I'm programming a random event system that happens to users when logged in and I put the below piece of code into my include file.
$tehchance = mt_rand(1,15);
if ($tehchance == "1"){
$thewin = 10;
mysql_query("UPDATE members SET Points = Points + $thewin WHERE Handle = '$members[Handle]'");
}
I also have this for another event:
if ($tehchance == "2"){
$thekhwin = 5;
$thexpwin = 10;
mysql_query("UPDATE members SET Points = Points - $thekhwin WHERE Handle = '$members[Handle]'");
mysql_query("UPDATE members SET XP = XP + $thexpwin WHERE Handle = '$members[Handle]'");
}
The code will work but sometimes when $tehchance is equal to something else other than 1 or 2, it'll just ignore my conditions and update the members table without satisfying the if statement. From testing, it'll randomly add points or subtract points. I printed the random number from $tehchance and it still adds points even when it isn't equal to 1 or 2. Then sometimes it doesn't do anything to the members table. Really confused here.
Any ideas?
Try using an if-then-else and debug that.
$tehchance = mt_rand(1,15);
if ($tehchance === 1){
echo 'doing 1';
$thewin = 10;
mysql_query("UPDATE members SET Points = Points + $thewin WHERE Handle = '$members[Handle]'");
} else if ($tehchance === 2){
echo 'doing 2';
$thekhwin = 5;
$thexpwin = 10;
mysql_query("UPDATE members SET Points = Points - $thekhwin WHERE Handle = '$members[Handle]'");
mysql_query("UPDATE members SET XP = XP + $thexpwin WHERE Handle = '$members[Handle]'");
} else {
echo 'doing nothing';
}
because you are comparing to a string : "1" instead of the number 1 (without quotes)
Related
foreach ($_POST as $nazwa_checkboxa=>$id) {
$s = "SELECT uprawnienie FROM user WHERE Id_user=".$id;
$helpdesk = 0;
if ($s == 0) {
$helpdesk = 1;
}
$z = "UPDATE user SET uprawnienie = ".$helpdesk." WHERE Id_user=".$id;
$wynik = $polaczenie->query($z);
$zmienione++;
}
Column uprawnienie return 0 = normal user and 1 = administrator
The update always set value to 1 and I can change user to administrator (0 to 1) but it doesnÄ…t work 1 to 0
Actually, you can do it using one query, e.g.:
update user
set uprawnienie = (SELECT if(uprawnienie=1,0,1) FROM user WHERE Id_user = '<id>')
where Id_user = '<id>'
Looks like you haven't actually run the query() for $s. Therefore, the if ($s==0) is not checking the query results, but rather whether "SELECT..."==0. Per the PHP docs, "Strings will most likely return 0" when cast to integers for such comparisons.
I am trying to make a script to check if an int is already added to my database. If so, it will re-generate another random number and check again. If it doesn't exist, it'll insert into the database.
However, I am having troubles. If a number exists, it just prints out num exists, how would I re-loop it to check for another and then insert that? I have tried to use continue;, return true; and so on... Anyway, here is my code; hopefully someone can help me!
<?php
require_once("./inc/config.php");
$mynum = 1; // Note I am purposely setting this to one, so it will always turn true so the do {} while will be initiated.
echo "attempts: ---- ";
$check = $db->query("SELECT * FROM test WHERE num = $mynum")or die($db->error);
if($check->num_rows >= 1) {
do {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')")or die($db->error);
echo "$newnum - CAN INSERT#!#!#";
break;
}
} while(0);
}
?>
I think the logic you're looking for is basically this:
do {
$i = get_random_int();
} while(int_exists($i));
insert_into_db($i);
(It often helps to come up with some functions names to simplify things and understand what's really going on.)
Now just replace the pseudo functions with your code:
do {
$i = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $i")or die($db->error);
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
$db->query("INSERT test (num) VALUES ('$i')") or die($db->error);
Of course, you can do a little more tweaking, by shortening...
// ...
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
...to:
// ...
$int_exists = $newcheck->num_rows >= 1;
} while($int_exists);
(The result of the >= comparison is boolean, and as you can see, you can assign this value to a variable, too, which saves you 4 lines of code.)
Also, if you want to get further ahead, try to replace your database calls with actual, meaningful functions as I did in my first example.
This way, your code will become more readable, compact and reusable. And most important of all, this way you learn more about programming.
The logic is incorrect here. Your do-while loop will get executed only once (as it's an exit-controlled loop) and will stop on the next iteration as the while(0) condition is FALSE.
Try the following instead:
while($check->num_rows >= 1) {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if ($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')") or die($db->error);
echo "$newnum - CAN ISNERT#!#!#";
break;
}
}
Sidenote: As it currently stands, your query is vulnerable to SQL injection and could produce unexpected results. You should always escape user inputs. Have a look at this StackOverflow thread to learn how to prevent SQL injection.
Here is an example of some code that I threw together using some of my previously made scripts. You will notice a few changes compared to your code, but the concept should work just the same. Hope it helps.
In my example I would be pulling the database HOST,USER,PASSWORD and NAME from my included config file
require_once("./inc/config.php");
echo "attempts: ---- ";
$running = true;
while($running == true) {
//create random number from 1-5
$newnum = rand(1,5);
//connect to database
$mysqli = new mysqli(HOST, USER, PASSWORD, NAME);
//define our query
$sql = "SELECT * FROM `test` WHERE `num` = '".$$newnum."'";
//run our query
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//check results, if num_rows >= our number exists
if (mysqli_num_rows($check_res) >= 1){
echo $newnum . " exists! \n";
}
else { //our number does not yet exists in database
$sql = "INSERT INTO `test`(`num`) VALUES ('".$newnum."')";
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
if ($check_res){
echo $newnum . " - CAN ISNERT#!#!#";
// close connection to datbase
mysqli_close($mysqli);
}
else{
echo "failed to enter into database";
// close connection to database
mysqli_close($mysqli);
}
break;
}
}
I would also like to note that this will continue to run if all the numbers have been used, you may want to put in something to track when all numbers have been used, and cause a break to jump out of the loop.
Hope this helps!
I'm new to AJAX and jQuery. I'm trying to pass a number from unrate.php to be used as checkVal (as shown below). The file does a bunch of stuff but it only echos the number. When I add a alert(checkVal) it shows a invalid character and than the number I want. (I just want the number)...
ajax handler:
$.get("unrate.php?numb="+ID, function(checkVal){
if (checkVal == 1) {
number.innerHTML = addNumb + 1;
} else {
number.innerHTML = addNumb - 1;
}
});
unrate.php:
<?php
$uNum = $_SESSION['userNum'];
$ider = $_GET['numb'];
$sql = mysql_query("SELECT * FROM ratecheck WHERE ID =".$ider);
$checkRay = mysql_fetch_array($sql);
$checkVal = $checkRay[$uNum];
$sqlZ = mysql_query("UPDATE ratecheck SET `".$uNum."`=0 WHERE ID=".$ider)
or die(mysql_error());
$sqlB = mysql_query("SELECT * FROM sources WHERE ID =".$ider);
$sourceRay = mysql_fetch_array($sqlB);
$newRC = $sourceRay['ratecount'] - 1;
mysql_query("UPDATE sources SET ratecount =".$newRC." WHERE ID =".$ider)
or die(mysql_error());
if ($checkVal > 1)
{
$newpts = $sourceRay['points'] - 1;
$userEmail = $sourceRay['user'];
mysql_query("UPDATE sources SET points =".$newpts." WHERE ID =".$ider)
or die(mysql_error());
if ($_SESSION['userName'])
{
$findUser = mysql_query("SELECT * FROM users WHERE email LIKE '".$userEmail."'") or mysql_error();
$currentRate = mysql_fetch_array($findUser);
$newrating = $currentRate['rating'] - 1;
mysql_query("UPDATE users SET rating =".$newrating." WHERE email LIKE '".$userEmail."'")
or mysql_error();
}
else
{
die('ERROR');
}
}
else
{
$newpts = $sourceRay['points'] + 1;
$userEmail = $sourceRay['user'];
mysql_query("UPDATE sources SET points =".$newpts." WHERE ID =".$ider)
or die(mysql_error());
if ($_SESSION['userName'])
{
$findUser = mysql_query("SELECT * FROM users WHERE email LIKE '".$userEmail."'") or mysql_error();
$currentRate = mysql_fetch_array($findUser);
$newrating = $currentRate['rating'] + 1;
mysql_query("UPDATE users SET rating =".$newrating." WHERE email LIKE '".$userEmail."'")
or mysql_error();
}
else
{
die('ERROR');
}
}
echo $checkVal;
mysql_close();
?>
Extra characters at the beginning or end of your output are something you occasionally run into with php. I greatly endorse the comment that suggests looking at the raw output from the server. You might also want to think about these possibilities:
Invisible characters at the beginning or end of your script file. Use a text editor that will show you hidden characters (even a hex editor) and see if there are any. Also, you don't have to end your php script with ?> if you're not doing anything else past it. You can just leave it open, as that will prevent characters showing up at the end.
Check the character encoding that your script has. This might not be the solution, but some time ago I had a similar situation that went away when I changed the encoding to UTF8 without Byte-Order Mark. Try doing the same thing and see if that fixes it
I am having difficulty updating a range of columns using mysql. My overall goal is to give the user the ability to change a list item's position and to have all of the other list items shift position to accommodate for the change. So say you have a range of numbers, 1-6 and you would like to move the item in position 2 to position 4 and have each item compensate for the change while each occupying only a single position number. I have been working on this for a few hours now and I am getting too tired to think straight. I am still very much a newbie with mysql but I have almost finished making my first cms except for this last annoying tidbit.
The code in question is:
$newposition = $_POST['position'];
$oldposition = $_GET['oldposition'];
$id = $_GET['id'];
while ($work = mysql_fetch_array($workset)) {
if ($newposition>$oldposition) {
mysql_query('UPDATE work SET position=position-1 WHERE position<='.$newposition.' AND position>'.$oldposition.'');
mysql_query('UPDATE work SET position='.$newposition.' WHERE id='.$id.'');
}
elseif
($newposition<$oldposition) {
mysql_query('UPDATE work SET position=position+1 WHERE position<'.$oldposition.' AND position<='.$newposition.'');
mysql_query('UPDATE work SET position='.$newposition.' WHERE id='.$id.'');
}
elseif
($newposition==$oldposition) {
echo 'same value! ';
}
}
It creates the requested position change correctly but all of the other numbers in the range get changed to an incorrect value. It is probably a simple mistake..
See this line -
mysql_query('UPDATE work SET position=position+1 WHERE position<'.$oldposition.' AND position<='.$newposition.'');
Are you sure its correct ?
I think it should be
mysql_query('UPDATE work SET position=position+1 WHERE position > '.$oldposition.' AND position <= '.$newposition.'');
So, I came up with a solution for anyone that is interested. It isn't the cleanest, but it appears to have worked..
if ($newposition>$oldposition) {
for ($i=$oldposition+1; $i<=$newposition; $i++) {
$workset = mysql_query('SELECT * FROM work WHERE position='.$i.' LIMIT 1', $connection);
while ($work = mysql_fetch_array($workset)) {
mysql_query('UPDATE work SET position='.$i.'-1 WHERE position='.$i.'');
mysql_query('UPDATE work SET position='.$newposition.' WHERE id='.$id.'');
}
}
}
elseif
($newposition<$oldposition) {
for ($i=$oldposition-1; $i>=$newposition; $i--) {
$workset = mysql_query('SELECT * FROM work WHERE position='.$i.' LIMIT 1', $connection);
while ($work = mysql_fetch_array($workset)) {
mysql_query('UPDATE work SET position='.$i.'+1 WHERE position='.$i.'');
mysql_query('UPDATE work SET position='.$newposition.' WHERE id='.$id.'');
}
}
}
elseif
($newposition==$oldposition) {
}
I have a rating system that uses the following equation to generate the rating average:
((Old Rating*Old Times Amount)+New Rating)/New Rating amount
However, if the current rating is 3, and it's been rated once, when I rate it three, it says the new rating is 2.5
What is the error here? Here's the full code.
<?php
session_start();
include("lib/db.php");
$db = new DBConnect;
if(isset($_POST['rating']) && is_numeric($_POST['rating']) && is_numeric($_POST['story']))
{
if($_POST['rating'] > 5 || $_POST['rating'] < 1){die("INVALID RATING");}
$rating = mysql_real_escape_string($_POST['rating']);
$story = mysql_real_escape_string($_POST['story']);
$c = $db->query("SELECT * FROM cdb_stories WHERE id=$story");
$c = mysql_fetch_array($c);
$u_name = mysql_real_escape_string($_SESSION['logged_in']);
$uid = $db->query("SELECT id FROM cdb_users WHERE username='{$u_name}'");
if(mysql_num_rows($uid) < 1){die("NOT LOGGED IN");}
$uid = mysql_fetch_array($uid);
$ratingd = $db->query("SELECT * FROM cdb_ratings WHERE userid='{$uid['id']}'");
if(mysql_num_rows($ratingd) > 0)
{
$ratingd = mysql_fetch_array($ratingd);
$new_rate = (($c['rating']*$c['rating_amt'])-$ratingd['rating']+$rating)/$c['rating_amt'];
$db->query("UPDATE cdb_stories SET rating={$new_rate} WHERE id={$story}");
$db->query("UPDATE cdb_ratings SET rating={$rating} WHERE userid='{$uid['id']}'");
die();
}
$new_num = $c['rating_amt']+1;
$new_rate = (($c['rating']*$c['rating_amt'])+$rating)/$new_num;
$db->query("UPDATE cdb_stories SET rating_amt={$new_num}, rating={$new_rate} WHERE id={$story}");
$db->query("INSERT INTO cdb_ratings VALUES({$uid['id']},{$rating},{$story})");
}
else
{
die("INVALID FIELDS");
}
?>
((Rating * Times) + New) / (Times + 1)
For your values:
((3 * 1) + 3) / (1 + 1)
= ( 3 + 3) / 2
= 6 / 2
= 3
So the procedure looks mathematically correct.
I suggest you put the calculation into a function of it's own with parameters, so you don't get irritated so much by the rest of the code you have in that batch. This will make it easier to debug for you:
function new_rate($rating, $times, $new)
{
return (($rating * $times) + $new) / ($times + 1);
}
You can then use that more easily within your code. Additionally if something else is the cause of the error, you can simply find out by testing the bare function. If it acts correct, you know that the error is placed somewhere else.
Hope this helps.