Select Next Row Needed In Query - php

So I have an attack system on my game where players use weapons they have purchased and can attack each other. Well they also have friends who they fight with and you level up in the game. For each level you can fight with 5 more people so it's like this: Level * 5 = Mob Available For example: I'm level 5 and have 100 Friends; I can fight with 25 of those friends and use 25 weapons in each category. here's a ScreenShot So Say in the Melee Category, I have 10 Knives, 5 Baseball Bats, And 10 Axes. How would I set it up to use the best attack Weapons? Here's the code I'm using now to limit and select 1 weapon at the moment:
if($level >= 100) {
if($mob_size >=500) {
$a_melee_avail = 500 + $hired_guns;
}
else {
$a_melee_avail = $total_mob;
}
}
if($level < 100) {
if($mob_size > $level * 5) {
$a_melee_avail = $level * 5;
}
else {
$a_melee_avail = $mob_size;
}
}
$check_a_melee = mysql_query("SELECT * FROM weapons WHERE owner_id=".$id." AND type='melee' AND owned>=".$a_melee_avail." LIMIT 1");
$check_a_mel_info = mysql_fetch_array($check_a_melee);
$a_mel_limit_plus1 = ($check_a_mel_info['id'] + 1);
// Checking melee owned
if(mysql_num_rows($check_a_melee) == 0) {
$a_get_melee = mysql_query("SELECT * FROM weapons WHERE owner_id=".$id." AND type='melee' AND owned<=".$a_melee_avail." ORDER BY attack DESC LIMIT 1");
}
if(mysql_num_rows($check_a_melee) == 1) {
$a_get_melee = mysql_query("SELECT * FROM weapons WHERE owner_id=".$id." AND type='melee' AND owned>=".$a_melee_avail." ORDER BY attack DESC LIMIT 1");
}
$a_melee = mysql_fetch_array($a_get_melee);
$a_melee_name = $a_melee['name'];
$a_melee_attack = $a_melee['attack'];
$a_melee_owned = $a_melee['owned'];
// Checking Availability
if($a_melee_owned >= $a_melee_avail) {
$a_melee_used = $a_melee_avail;
}
if($a_melee_owned < $a_melee_avail) {
$a_melee_used = $a_melee_owned;
}
$a_melee_damage = $a_melee_attack * $a_melee_used;
But that just select 1 of the best weapons based on attack, How could I set it to where they use all available weapons?

Could you use sortfeild
function __construct($sortField)
{
$this->sortField = $sortField;
}
public function compare($a, $b)
{
return strnatcmp($b[$this->sortField], $a[$this->sortField]);
}
}
And the your array could be used in a list right?

Related

Paging, Limit Paging number php

How can I limit the paging number in php?
i mean like this, example:
1 2 3 4 5
if number 3 clicked like this:
1 .. .. 4 5
or like this:
1 2 3 .. 5
or
.. 2 3 4 ..
so if too many paging numbers do not show all numbers
this my code:
$default_index = 0;
$default_batas = 2;
if(isset($_GET['batas']))
{
$default_batas = $_GET['batas'];
}
if(isset($_GET['halaman']))
{
$default_index = ($_GET['halaman']-1) * $default_batas;
}
$ambil_data = mysql_query("SELECT * FROM mytable ORDER BY id ASC Limit ".$default_index.", ".$default_batas);
$total_baris = mysql_num_rows(
mysql_query("SELECT * FROM mytable")
);
$nomor_paging = 1;
$html_paging = "<div>";
while($total_baris - $default_batas > 0)
{
$html_paging .= "<center><div><a href='?halaman=".$nomor_paging."&batas=".$default_batas."'>".$nomor_paging."</a></div>";
$nomor_paging++;
$total_baris -= $default_batas;
}
if($total_baris > 0)
{
$html_paging .= "<div><a href='?halaman=".$nomor_paging."&batas=".$default_batas."'>".$nomor_paging."</a></div></center>";
}
$html_paging .= "</div><br/>";
this the output code :
<?php echo $output_html?>
<?php echo $html_paging?>

Very simple LIMIT query trouble is blocking me

I have the following PHP code:
$page = $_POST["page"];
$pageSize = $_POST["pageSize"];
$toRecord = $page * $pageSize;
$fromRecord = $toRecord - $pageSize;
$query = "SELECT * FROM table LIMIT $fromRecord, $toRecord";
Now, out of 10 total table records, if my $pageSize is '3', the first page returns me 3 records, the 2nd 6 records, the 3rd 4 records, and the last one 1 record. I have limited experience in SQL, what am I doing wrong?
LIMIT params are offset, row_count. So you should use not $toRecord, but $pageSize there - and don't forget about escaping it. In fact, I'd rewrite this logic a bit:
define('DEFAULT_PAGE_NO', 1);
define('DEFAULT_PAGE_SIZE', 10);
if (isset($_POST['page']) {
$pageNo = max(DEFAULT_PAGE_NO, (int)$_POST['page']);
}
else {
$pageNo = DEFAULT_PAGE_NO;
}
if (isset($_POST['pageSize']) {
$pageSize = (int)$_POST['pageSize'];
if ($pageSize <= 0) {
$pageSize = DEFAULT_PAGE_SIZE;
}
}
else {
$pageSize = DEFAULT_PAGE_SIZE;
}
$offset = ($pageNo - 1) * $pageSize;
$query = "SELECT * FROM table LIMIT $offset, $pageSize";

Select Query in Group of 10

I followed one link here, and modified my code accordingly. What I am trying to do achieve is for example a table name media_ids contains 45 rows(which is dyanamic), I want to divide the no of rows in a group of 10 rows minimum (in my case four groups of 10 rows and 1 group of 5) and execute code of each group per hour.
For example from select record from id 1 to 10 then second hour from 11 to 20 and so on unless fetches the last record and start again from id 1.
I added a tracker, which check whats the current limit and proceed.But its giving me the required result what I am trying to achieve.
<?php
require('inc/dbConnect.php');
$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];
$lastPointer10=$lastPointer+10;
$currentMediaQuery = "select * from media_ids where id > ".$lastPointer." limit ".$lastPointer.",".$lastPointer10."";
$mediaQuery = mysqli_query($con, $currentMediaQuery);
if (mysqli_num_rows($mediaQuery) > 0) {
while ($row = mysqli_fetch_assoc($mediaQuery)) {
// do stuff…
echo $id=$row['id']."<br>";
}
}
else
{echo "0";}
if ($lastPointer + 10 > 40) {
$lastPointer = 1;
} else {
$lastPointer += 10;
}
mysqli_query($con, "update media_tracker set tracker = $lastPointer");
?>
I am assuming you are calling this script every hour via ajax/Js...
In your code if you delete some data from another script you may find your first row id i.e 100 !
require('inc/dbConnect.php');
$limit = 10 ;
$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];
$lastPointerRes = mysqli_fetch_assoc($lastPointerResult);
$lastPointer = empty($lastPointerRes['tracker']) ? 0 : $lastPointerRes['tracker'] ;
$lastPointer10=$lastPointer* $limit;
$currentMediaQuery = "select * from media_ids limit ".$limit." OFFSET ".$lastPointer10."";
$mediaQuery = mysqli_query($con, $currentMediaQuery);
if (mysqli_num_rows($mediaQuery) > 0) {
while ($row = mysqli_fetch_assoc($mediaQuery)) {
// do stuff…
echo $id=$row['id']."<br>";
}
}
else
{echo "0";}
//do a total row count query here and set as value of $total rather than 40
$total =40 ;
$flag = ceil($total/$limit);
if ($lastPointer == $flag) {
$lastPointer = 0;
} else {
$lastPointer ++;
}
mysqli_query($con, "update media_tracker set tracker = $lastPointer");

Alphabetically ordered list from mysqli join query

I am trying to print out an alphabetically ordered list of usernames after using a mysqli join query to select userid's from a friends table.
Friends table consists of
id - userid_one - userid_two - friendship_date - friendship_type
Users table has a pretty standard layout, and the only field I really need from it is the username (to display) and the userid to link the two tables
what i want to achieve is the below
A
Andy
Anna
B
Bobby
Brian
The code i am using is below.
$ir['userid'] //the current users id
$getfriends = mysqli_query($con,"SELECT * FROM friends INNER JOIN users ON (friends.userid_one = users.userid OR friends.userid_two = users.userid) WHERE (userid_one = '{$ir['userid']}' OR userid_two = '{$ir['userid']}') ORDER BY username") or die("query error");
$last="";
if(mysqli_num_rows($getfriends) == 0)
{
print"<li>You have no friends....sorry</li>";
}
else
{
while($gotf=mysqli_fetch_array($getfriends))
{
if($gotf['userid_one'] == $ir['userid']){$friend = $gotf['userid_two'];}else{$friend = $gotf['userid_one'];}
$printed_array = explode(",",$printed);
if(!in_array($friend,$printed_array))
{
$username_of_user = get_username_no_link($friend);
$current_letter = $username_of_user[0];
if ($last != $current_letter) {
print"<li class='Label'>{$current_letter}</li>";
$username_of_user = get_username_nd_avatar($friend);
print"<li>".$username_of_user."</li>";
$last = $current_letter;
$printed = $printed.",".$friend;
}
elseif($last == $current_letter){
$username_of_user = get_username_nd_avatar($friend);
print"<li>".$username_of_user."</li>";
$last = $current_letter;
$printed = $printed.",".$friend;
}
}
}
}
I have not got much experience of using JOIN in mysqli queries and my issue is that I am not getting the list sorted alphabetically as the below example shows.
A
Andy
T
Thomas
S
Sandra
Sally
UPDATE--
the order in which the usernames display, now seems to change randomly after reloading the page, which is further confusing the matter!
question now answered after some playing around. Ended up putting the usernames into an array, then sorting the array alphabetically by value, as well as adding a $printed_array array to add each friend to after they were printed to prevent them being printed out twice.
$usersnames = array();
while($gotf=mysqli_fetch_array($getfriends))
{
if($printed != ""){$comma = ",";}
if($gotf['userid_one'] == $ir['userid']){$friend = $gotf['userid_two'];}else{$friend = $gotf['userid_one'];}
$printed_array = explode(",",$printed);
if(!in_array($friend,$printed_array))
{
$username_of_user = get_username_no_link($friend);
$usersnames[] = $username_of_user;
$printed = $printed.$comma.$friend;
}
}
sort($usersnames);
foreach($usersnames as $name)
{
$getuserid = mysqli_query($con,"SELECT userid,avatar FROM users WHERE username = '$name' LIMIT 1");
$gotuserid = mysqli_fetch_array($getuserid);
//var_dump($gotuserid);
$displaypic = "<img style='height:30px;vertical-align:middle;margin:5px;' src='".$gotuserid['avatar']."'>";
$current_letter = $name[0];
if ($last != $current_letter)
{
print"<li class='Label'>{$current_letter}</li>";
print"<li><a href='profile/".$name."'>".$displaypic.$name."</a></li>";
$last = $current_letter;
}
elseif($last == $current_letter)
{
print"<li><a href='profile/".$name."'>".$displaypic.$name."</a></li>";
$last = $current_letter;
}
}

PHP sorting array output

UPDATE 2 (Players Handicap Index Calculation)
$sql3 = "SELECT roundID FROM rounds WHERE userID='$userID'";
$result3 = mysql_query($sql3) or die(mysql_error());
$total_rounds = mysql_num_rows($result3);
//CALCULATE USER HANDICAP INDEX IF TOTAL_ROUNDS > 4
if($total_rounds > 4){
if($total_rounds<7) { $score_count = 1; }
elseif($total_rounds<9) { $score_count = 2; }
elseif($total_rounds<11) { $score_count = 3; }
elseif($total_rounds<13) { $score_count = 4; }
elseif($total_rounds<15) { $score_count = 5; }
elseif($total_rounds<17) { $score_count = 6; }
elseif($total_rounds<18) { $score_count = 7; }
elseif($total_rounds<19) { $score_count = 8; }
elseif($total_rounds<20) { $score_count = 9; }
else { $score_count = 10; }
$sql2 = "SELECT differential FROM rounds WHERE userID='$userID' ORDER BY date DESC LIMIT 20";
$result2 = mysql_query($sql2) or die(mysql_error());
$diff_results = array();
while($row = mysql_fetch_assoc($result2)){
$diff_results[] = $row['differential'];
}
sort($diff_results);
$diff_results = array_slice($diff_results, 0, $score_count);
$handicapIndex = array_sum($diff_results) / $score_count * 0.96;
$handicapIndex = (floor($handicapIndex * 10)) / 10;
Hopefully this will give you all and idea of how I calculate a players handicap index. Now I would like to show the player (user) the rounds (date ordered) that are used to calculate his index.
Always appreciative!
UPDATE (structure of rounds table)
roundID - auto incrementing primary key
userID - INT
courseID - INT
tee - VARCHAR
differential - FLOAT
date - DATE
I am struggling to even get started with this feature I am trying to implement. Any help would be much appreciated.
I have a set of mysql db results I would like to sort by field differential. I pull them out of the db like this:
$sql4 = "SELECT * FROM rounds WHERE userID='$userID' ORDER BY date DESC LIMIT 20";
$result4 = mysql_query($sql4) or die(mysql_error());
$total_rounds = mysql_num_rows($result4);
As you can see above I counted the rows returned to run through this if-elseif-else statement to figure out how many scores I need to highlight with different css:
if($total_rounds<7) { $score_count = 1; }
elseif($total_rounds<9) { $score_count = 2; }
elseif($total_rounds<11) { $score_count = 3; }
elseif($total_rounds<13) { $score_count = 4; }
elseif($total_rounds<15) { $score_count = 5; }
elseif($total_rounds<17) { $score_count = 6; }
elseif($total_rounds<18) { $score_count = 7; }
elseif($total_rounds<19) { $score_count = 8; }
elseif($total_rounds<20) { $score_count = 9; }
else { $score_count = 10; }
For example, if $total_rounds = 16 my $score_count would be 6.
Now I need to take this data set of 16 rows and spit it out with php so I maintain my ORDER BY date while applying a different css format to the 6 figured in the above if-elseif-else statement. The $score_count is figured because I need to highlight (aka apply different css) to the 6 lowest scores of the 16 row data set WHILE maintaining my date order.
The desired output would look like this (with the * denoting the separate css format *).
01-08-2013 - 16
01-07-2012 - 1 *
01-06-2013 - 15
01-05-2012 - 2 *
01-04-2013 - 14
01-03-2012 - 3 *
01-02-2013 - 13
01-01-2012 - 4 *
12-31-2012 - 12
12-30-2012 - 5 *
12-29-2012 - 11
12-28-2012 - 6 *
12-27-2012 - 10
12-26-2012 - 9
12-25-2012 - 8
12-24-2012 - 7
Please let me know if you have questions.
Thanks
There are couple of steps that you will have to follow.
1) Sort the results with score(differential) and get the ids of the six records having lowest score.
$sql4 = "SELECT * FROM rounds WHERE userID='$userID' ORDER BY differential LIMIT 20";
$result4 = mysql_query($sql4) or die(mysql_error());
$total_rounds = mysql_num_rows($result4);
if($total_rounds<7) { $score_count = 1; }
elseif($total_rounds<9) { $score_count = 2; }
elseif($total_rounds<11) { $score_count = 3; }
elseif($total_rounds<13) { $score_count = 4; }
elseif($total_rounds<15) { $score_count = 5; }
elseif($total_rounds<17) { $score_count = 6; }
elseif($total_rounds<18) { $score_count = 7; }
elseif($total_rounds<19) { $score_count = 8; }
elseif($total_rounds<20) { $score_count = 9; }
else { $score_count = 10; }
$idsArray = array();
for($i=0; $i<$score_count; $i++){
$dets = mysql_fetch_array($result4);
$idsArray[] = $dets['roundID'];
}
2) Loop over records and match the id in array that you have made by first step. If id matches apply CSS otherwise not.
$sql4 = "SELECT * FROM rounds WHERE userID='$userID' ORDER BY date DESC LIMIT 20";
$result4 = mysql_query($sql4) or die(mysql_error());
while($dets = mysql_fetch_array($result4)){
if(in_array($dets['roundID'], $idsArray)){
//apply CSS
//display details here
}
else{
//display details here
}
}
Note: You should stop using mysql_* now. Its highly recommended by experts to use mysqli_* instead
I will take your example of $total_rounds = 16 my $score_count would be 6.
$total_rounds = 16;
$score_count = 6 // comes from the if-else loop you already have
// now we loop over the result
// the css is applied to every odd result, until $score_count is not 0
$counter = 0;
while( ( $data = mysql_fetch_assoc( $result4 ) ) !== false ) {
if( ( $counter % 2 ) && $score_count ) {
echo $data['date']; // apply your css here
} else {
echo $data['date'];
}
$counter++;
$score_count--;
}
Hope this helps.

Categories