Users get pass simple If check - php

I have a browser game where you can upgrade your attack,defence,spies and patrol by clicking on submit button. every upgrade cost X gold and X food.
this is the address to the game (it's in hebrew):
http://www.mafia.co.il
In the last few days some users found a way to upgrade it without having enough gold/food. The result is that they have minus in that resource of the game. ofcourse I thought I blocked this option.
also, for some reason they are able to upgrade it more then 10 times - when you'll read the code you'll see that I at least try to block that option.
Please does someone have any idea where is the problem?
This is the upgrade code (I translate the hebrew parts to english, I also added notes):
the reason for the foreach loop is to get the name of the $_POST.
elseif (isset($_POST['attack']) || isset($_POST['defence']) || isset($_POST['spies']) || isset($_POST['patrols'])) {
// Get user details
$ud = details($user_id);
foreach($_POST as $name => $val) {
// Number came with ','. So here i'm removing it.
$pr['gold'] = str_replace(',','',get_upg_price($ud['cvl'][$name]));
$pr['food'] = str_replace(',','',get_upg_price($ud['cvl'][$name]));
// Check if the user has enough food and gold.
if (check_rsc($pr,$ud)) {
// Check if user has maximum upgrade possible.
if ($ud['cvl'][$name] < 10) {
mysql_query("UPDATE `civ_level` SET ".$name."=".$name."+1 WHERE ID='".$user_id."'");
mysql_query("UPDATE `resources` SET gold=gold-'".$pr['gold']."', food=food-'".$pr['food']."' WHERE ID='".$user_id."'");
update_power($user_id);
} else {
$error = "<tr><td colspan='8' style='color:black; background: #CC3333; border:1px solid white;'>you are at maximum possible upgrade.</td></tr>";
}
} else {
$error = "<tr><td colspan='8' style='color:black; background: #CC3333; border:1px solid white;'>You dont have enough resources.</td></tr>";
}
}
}
Function details:
function details($id) {
$select1 = mysql_query("SELECT * FROM `users` WHERE ID='".$id."'");
$sel = mysql_fetch_array($select1);
$array['usr'] = $sel;
$select2 = mysql_query("SELECT * FROM `user_d` WHERE ID='".$id."'");
$sel2 = mysql_fetch_array($select2);
$array['usd'] = $sel2;
$select3 = mysql_query("SELECT * FROM `resources` WHERE ID='".$id."'");
$sel3 = mysql_fetch_assoc($select3);
$array['rsc'] = $sel3;
$select4 = mysql_query("SELECT * FROM `train_price`");
$sel4 = mysql_fetch_assoc($select4);
$array['trp'] = $sel4;
$select5 = mysql_query("SELECT * FROM `civ_level` WHERE ID='".$id."'");
$sel5 = mysql_fetch_array($select5);
$array['cvl'] = $sel5;
if (empty($array['usd'])) {
return false;
} else {
return $array;
}
}
Function get_upg_price:
function get_upg_price($level) {
$a = 0;
$price = 100;
while ($a<$level) {
$price = $price*3;
$a++;
}
return number_format($price);
}
Function check_rsc:
function check_rsc($array,$ud) {
foreach ($array as $name => $val) {
if ($ud['rsc'][$name] < $val) {
return false;
}
}
return true;
}
Example of an input:
<form method='post'><input type='submit' name='attack' value='train' />
Thank you!

Always but always Use addslashes($userInput),
The addslashes function will keep you safe from the sql injection and preventing you from users to cheat on the game.
Never let the variable go directly on the database
That is your error

Related

How to prevent undefined variable error from showing? (I know the variable is null in this case)

For part of a project i am working on in school i am building a room booking system. As part of this system, i have a page where users can enter criteria for a room and the page will return available rooms that fit that criteria and are free for booking. If a users search does not return any results i intend to lower the criteria entered, display a room that fits the altered criteria and display a message to the user informing them of the altered criteria. The call to function suggestroom() is shown here.
} else {
$reducecapacity = 1;
do {
$booking = new Booking();
$suggestedrooms = $booking->suggestroom(($capacity - $reducecapacity), $appletv, $printer);
$reducecapacity = $reducecapacity + 1;
} while($suggestedrooms === null);
echo 'This room has a cacpacity of: ' . ($capacity-($reducecapacity-1));
for($x=0; $x<count($suggestedrooms); $x++) {
echo $suggestedrooms[$x];
}
}
Public function SuggestRoom($capacity, $appletv, $printer) {
if($appletv == 1 and $printer ==0) {
$roomname = DB::GetInstance()->query("SELECT roomname FROM room WHERE capacity >= '$capacity' AND appletv ='$appletv'");
} elseif($appletv == 0 and $printer == 1) {
$roomname = DB::GetInstance()->query("SELECT roomname FROM room WHERE capacity >= '$capacity' AND printer = '$printer'");
} elseif($appletv == 1 and $printer == 1) {
$roomname = DB::GetInstance()->query("SELECT roomname FROM room WHERE capacity >= '$capacity' AND appletv ='$appletv' AND printer = '$printer'");
} else {
$roomname = DB::GetInstance()->query("SELECT roomname FROM room WHERE capacity >= '$capacity'");
}
$roomcount = $roomname->count();
if($roomcount == 0) {
echo 'No classes match your criteria';
} else {
for($x=0; $x<$roomcount; $x++) {
$RoomArray[$x] = $roomname->results()[$x]->roomname;
}
}
$LoopCount = 0;
$EndLoop = false;
$RNDnum = 0;
$availableroomcount = 0;
do {
$suggestedRoom = $RoomArray[$RNDnum];
$getRoomID = DB::GetInstance()->query("SELECT roomid FROM room WHERE roomname = '$suggestedRoom'");
$roomid = $getRoomID->results()[0]->roomid;
$bookingid = Input::get('bookingdate') . Input::get('period') . $roomid;
$CheckIfBooked = DB::GetInstance()->query("SELECT bookingid FROM booking WHERE bookingid = '$bookingid'");
if($CheckIfBooked->count() ==0) {
$availablerooms[$availableroomcount] = $suggestedRoom;
$availableroomcount = $availableroomcount+1;
}
if($LoopCount===$roomcount-1) {
$NoRoomMessage = true;
$EndLoop = true;
$suggestedRoom = null;
}
$LoopCount = $LoopCount+1;
$RNDnum = $RNDnum +1;
} while ($EndLoop <> 1);
return $availablerooms;
}
Thus, when there are no bookings, a null array will be returned to suggested rooms and this will continue until a room is found (if not, i will make it so other criteria is changed, not that far ahead yet).
A room can be found, and the code works however for x amount of times that the code is ran before a room is found i.e an empty array is returned, i get an undefined variable message. How can i get around this?
Switching off notices, warnings, errors is not the best way to code.
And unlike the above answers I prefer to always initialize a variable rather then using isset().
Use isset/empty
if(isset($var1) || !empty($var1)){
//do something
} else {
//do another
}

Working with multiple rows from a MySQL query

Before I begin, I want to point out that I can solve my problem. I've rehearsed enough in PHP to be able to get a workaround to what I'm trying to do. However I want to make it modular; without going too much into detail to further confuse my problem, I will simplify what I am trying to do so that way it does not detract from the purpose of what I'm doing. Keep that in mind.
I am developing a simple CMS to manage a user database and edit their information. It features pagination (which works), and a button to the left that you click to open up a form to edit their information and submit it to the database (which also works).
What does not work is displaying each row from MySQL in a table using a very basic script which I won't get into too much detail on how it works. But it basically does a database query with this:
SELECT * FROM users OFFSET (insert offset here) LIMIT (insert limit here)
Essentially, with pagination, it tells what number to offset, and the limit is how many users to display per page. These are set, defined, and tested to be accurate and they do work. However, I am not too familiar how to handle these results.
Here is an example query on page 2 for this CMS:
SELECT * FROM users OFFSET 10 LIMIT 10
This should return 10 rows, 10 users down in the database. And it does, when I try this command in command prompt, it gives me what I need:
But when I try to handle this data in PHP like this:
<?php
while ($row = $db->query($pagination->get_content(), "row")) {
print_r($row);
}
?>
$db->query method is:
public function query($sql, $type = "assoc") {
$this->last_query = $sql;
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
if ($type == "row") {
return mysql_fetch_row($result);
} elseif ($type == "assoc" || true) {
return mysql_fetch_assoc($result);
} elseif ($type == "array") {
return mysql_fetch_array($result);
} elseif ($type == false) {
return $result;
}
}
$pagination->get_content method is:
public function get_content() {
global $db;
$query = $this->base_sql;
if (!isset($_GET["page"])) {
$query .= " LIMIT {$this->default_limit}";
return $query;
} elseif (isset($_GET["page"]) && $_GET["page"] == 1) {
$query .= " LIMIT {$this->default_limit}";
return $query;
} elseif (isset($_GET["page"])) {
$query .= " LIMIT {$this->default_limit}";
$query .= " OFFSET " . (($_GET["page"] * $this->default_limit) - 10);
return $query;
}
}
And my results from the while loop (which should print out each row of the database, no?) gives me the same row everytime, continuously until PHP hits the memory limit/timeout limit.
Forgive me if its something simple. I rarely ever handle database data in this manner. What I want it to do is show the 10 users I requested. Feel free to ask any questions.
AFTER SOME COMMENTS, I'VE DECIDED TO SWITCH TO MYSQLI FUNCTIONS AND IT WORKS
// performs a query, does a number of actions dependant on $type
public function query($sql, $type = false) {
$sql = $this->escape($sql);
if ($result = $this->db->query($sql)) {
if ($type == false) {
return $result;
} elseif ($type == true || "assoc") {
if ($result->num_rows >= 2) {
$array;
$i = 1;
while ($row = $result->fetch_assoc()) {
$array[$i] = $row;
$i++;
}
return $array;
} elseif ($result->num_rows == 1) {
return $result->fetch_assoc();
}
} elseif ($type == "array") {
if ($result->num_rows >= 2) {
$array;
$i = 1;
while ($row = $result->fetch_array()) {
$array[$i] = $row;
$i++;
}
return $array;
} elseif ($result->num_rows == 1) {
return $result->fetch_array();
}
}
} else {
die("There was an error running the query, throwing error: " . $this->db->error);
}
}
Basically, in short, I took my entire database, deleted it, and remade another one based on the OOD mysqli (using the class mysqli) and reformatted it into a class that extends mysqli. A better look at the full script can be found here:
http://pastebin.com/Bc00hESn
And yes, it does what I want it to. It queries multiple rows, and I can handle them however I wish using the very same methods I planned to do them in. Thank you for the help.
I think you should be using mysql_fetch_assoc():
<?php
while ($row = $db->query($pagination->get_content())) {
print_r($row);
}
?>

PHP recently viewed script to session array

I've been given this bit of code:
if(isset($_GET['viewevent'])) {
if(count($_SESSION['e_lastviewed']) == 0) {
$_SESSION['e_lastviewed'][0] = $_GET['viewevent'];
} else if(!in_array($_GET['viewevent'], $_SESSION['e_lastviewed'])) {
$_SESSION['e_lastviewed'][2] = $_SESSION['e_lastviewed'][1];
$_SESSION['e_lastviewed'][1] = $_SESSION['e_lastviewed'][0];
$_SESSION['e_lastviewed'][0] = $_GET['viewevent'];
}
}
if($_GET['show']) {
$_SESSION['show'] = $_GET['show'];
} else if($_SESSION['show']=='') {
$_SESSION['show'] = "all";
}
It apparently saves ID's of recently viewed items, so i need to put these id's into an array.
Would this work?
$my_array = array($_SESSION['e_lastviewed'][2],$_SESSION['e_lastviewed'][1],$_SESSION['e_lastviewed'][0]);
I've ran it but it displays blank results (not sure if thats due to me not doing it right or incomplete code...Have i missed something? I'm not sure if i completley understand the script i was given...
try this:
if ( !isset($_SESSION['e_lastviewed']) )
$_SESSION['e_lastviewed'] = array();
// alt: while(count($_SESSION['e_lastviewed']) > 2 ) {
if(count($_SESSION['e_lastviewed']) > 2 ) {
array_shift($_SESSION['e_lastviewed']); // drop off from 3
array_unshift($_SESSION['e_lastviewed'],$_GET['viewevent']); // insert in the beginning
if($_GET['show']) {
$_SESSION['show'] = $_GET['show'];
} else if($_SESSION['show']=='') {
$_SESSION['show'] = "all";
}

One roll number cant be added again [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
same roll number can not be added
I want my code to behave this way that if once i had added a roll number, it can not be added again in the registration..........same as if once an email adress is registered the error displays that EMAIL ADDRESS ALREADY BEEN TAKEN....
I am creating a function . of roll numbr value is 1 it shall display error and if not 1 it shall not display the error
function selectroll($studentname,$rollnumber)
{
$sql = "SELECT * FROM tblstuden WHERE studentname = 'studentname' and rollnumber = '$rollnumber';";
$obj_db = new DB();
$obj_db->query($sql);
$row = $obj_db->rsset();
if{
$val = 1;
}
else{
$val = 0;
}
$obj_db->db_close();
return $val;
}
$this->_id($row[id]);
$this->_studentname($row[studentname]);
$this->_rollnumber($row[rollnumber]);
$this->_classname($row[classname]);
$obj_db->db_close();
}
}
?>
and the function is called at the page by this method
<?php
if(isset($_POST['btnSubmit']) and $_GET['action'] == "Add")
{
$val = $Tblstuden->selectroll($_POST['studentname'],$_POST['rollnumber']);
if ($val =='1')
{
$Tblstuden->copyPostData();
$Tblstuden->insert();
echo"asdf";
}
redirect("index.php?page=studentlist");
}
else
{
echo"abc";
}
?>
You probably want
function selectroll($studentname,$rollnumber)
{
$sql = "SELECT * FROM tblstuden WHERE studentname = 'studentname' and rollnumber = '$rollnumber';";
$obj_db = new DB();
$obj_db->query($sql);
$row = $obj_db->rsset();
if ($row){
$val = 1;
$this->_id($row[id]);
$this->_studentname($row[studentname]);
$this->_rollnumber($row[rollnumber]);
$this->_classname($row[classname]);
}
else{
$val = 0;
}
$obj_db->db_close();
return $val;
}
}
?>
in line 8 of the top function - as otherwise the code won't compile.
Sub-note, your code is subject to mysql injection, you should look at using PDO (http://php.net/manual/en/book.pdo.php) for your database functions before you get used to the old method. Please. Do it now ;)

Is there a piece of public code available to create a page index using PHP?

I have a MySQL table holding lots of records that i want to give the user access to. I don't want to dump the entire table to the page so i need to break it up into 25 records at a time, so i need a page index. You have probably seen these on other pages, they kind of look like this at the base of the page:
< 1 2 3 4 5 6 7 8 9 >
For example, when the user clicks on the '4' link, the page refreshes and the offset is moved on (4th page x 25 records). Here is what i already have:
function CreatePageIndex($ItemsPerPage, $TotalNumberOfItems, $CurrentOffset, $URL, $URLArguments = array())
{
foreach($URLArguments as $Key => $Value)
{
if($FirstIndexDone == false)
{
$URL .= sprintf("?%s=%s", $Key, $Value);
$FirstIndexDone = true;
}
else
{
$URL .= sprintf("&%s=%s", $Key, $Value);
}
}
Print("<div id=\"ResultsNavigation\">");
Print("Page: ");
Print("<span class=\"Links\">");
$NumberOfPages = ceil($TotalNumberOfItems / $ItemsPerPage);
for($x = 0; $x < $NumberOfPages; $x++)
{
if($x == $CurrentOffset / $ItemsPerPage)
{
Print("<span class=\"Selected\">".($x + 1)." </span>");
}
else
{
if(empty($URLArguments))
{
Print("".($x + 1)." ");
}
else
{
Print("".($x + 1)." ");
}
}
}
Print("</span>");
Print(" (".$TotalNumberOfItems." results)");
Print("</div>");
}
Obviously this piece of code does not create a dynamic index, it just dumps the whole index at the bottom of the page for every page available. What i need is a dynamic solution that only shows the previous 5 pages and next 5 pages (if they exist) along with a >> or something to move ahead 5 or so pages.
Anybody seen an elegant and reusable way of implementing this as i feel i'm re-inventing the wheel? Any help is appreciated.
Zend Framework is becoming a useful collection and includes a Zend_Paginator class, which might be worth a look. Bit of a learning curve and might only be worth it if you want to invest the time in using other classes from the framework.
It's not too hard to roll your own though. Get a total count of records with a COUNT(*) query, then obtain a page of results with a LIMIT clause.
For example, if you want 20 items per page, page 1 would have LIMIT 0,20 while page 2 would be LIMIT 20,20, for example
$count=getTotalItemCount();
$pagesize=20;
$totalpages=ceil($count/$pagesize);
$currentpage=isset($_GET['pg'])?intval($_GET['pg']):1;
$currentpage=min(max($currentpage, 1),$totalpages);
$offset=($currentpage-1)*$pagesize;
$limit="LIMIT $offset,$pagesize";
It's called Pagination:
a few examples:
A nice one without SQL
A long tutorial
Another tutorial
And Another
And of course.. google
How about this jQuery-plugin?
So all the work is done on the clientside.
http://plugins.jquery.com/project/pagination
demo: http://d-scribe.de/webtools/jquery-pagination/demo/demo_options.htm
Heres an old class I dug out that I used to use in PHP. Now I handle most of it in Javascript. The object takes an array (that you are using to split the stack into pages) and return the current view. This can become tedious on giant tables so keep that in mind. I generally use it for paging through small data sets of under 1000 items. It can also optionally generate your jump menu for you.
class pagination {
function pageTotal($resultCount, $splitCount) {
if (is_numeric($resultCount) && is_numeric($splitCount)) {
if ($resultCount > $splitCount) {
$pageAverage = (integer)$resultCount / $splitCount;
$pageTotal = ceil($pageAverage);
return $pageTotal;
} else {
return 1;
}
} else {
return false;
}
}
function pageTotalFromStack($resultArray, $splitCount) {
if (is_numeric($splitCount) && is_array($resultStack)) {
if (count($resultStack) > $splitCount) {
$resultCount = count($resultStack);
$pageAverage = (integer)$resultCount / $splitCount;
$pageTotal = ceil($pageAverage);
return $pageTotal;
} else {
return 1;
}
} else {
return false;
}
}
function makePaginationURL($preURL, $pageTotal, $selected=0, $linkAttr=0, $selectedAttr=0) {
if (!empty($preURL) && $pageTotal >= 1) {
$pageSeed = 1;
$passFlag = 0;
$regLink = '<a href="{url}&p={page}"';
if (is_array($linkAttr)) $regLink .= $this->setAttributes($linkAttr); //set attributes
$regLink .= '>{page}</a>';
$selLink = '<a href="{url}&p={page}"';
if (is_array($selectedAttr)) $selLink .= $this->setAttributes($selectedAttr); //set attributes
$selLink .= '>{page}</a>';
while($pageSeed <= $pageTotal) {
if ($pageSeed == $selected) {
$newPageLink = str_replace('{url}', $preURL, $selLink);
$newPageLink = str_replace('{page}', $pageSeed, $newPageLink);
} else {
$newPageLink = str_replace('{url}', $preURL, $regLink);
$newPageLink = str_replace('{page}', $pageSeed, $newPageLink);
}
if ($passFlag == 0) {
$passFlag = 1;
$linkStack = $newPageLink;
} else {
$linkStack .= ', ' . $newPageLink;
}
$pageSeed++;
}
return $linkStack;
} else {
return false;
}
}
function splitPageArrayStack($stackArray, $chunkSize) {
if (is_array($stackArray) && is_numeric($chunkSize)) {
return $multiArray = array_chunk($stackArray, $chunkSize);
} else {
return false;
}
}
}

Categories