PHP - position in table - php

How can I find the position a certain row has in my database table?
In my database I have a bunch of Players from a game. They have columns such as ID, name, level, world, and so on.
I want to sort them by Level, and see what position they are in in the list.
So far I've tried this, but it only prints out 0 (the start value I put). It does not seem to iterate through.
Previously I made sure the name is stored in $name.
$query = "SELECT * FROM rookstayers ORDER BY level DESC";
$globalPos = 0;
$result = mysql_query($query);
$num = mysql_numrows($result);
$i = 0;
while($i < $num) {
$posName = mysql_result($result, $i, 'name');
if($posName == '$name')
{
$globalPos = $i;
break;
}
$i++;
}
If my table looks like this (after sorting it by level):
name - level
Joe - 50
Jacob - 47
Sarah - 34
Anna - 19
Then "Sarah" would be number 3.
Anna number 4, etc...
I want the position-number to be in $globalPos.
I only found pure SQL code for this, but I want it in PHP. Is it not possible to do in PHP?

I'm not sure if this is the only problem:
If you use single quotes ', the string is not parsed for variables. If you want to compare a string stored in $name with a string stored in $posName, you should use $posName === $name. You could also use $posName === "$name", but the double quotes are unnecessary.
Notice also, that the mysql functions are deprecated. You should use mysqli or PDO_MySQL instead. (See Choosing an API)

<?php
/*
CREATE TABLE results
(name VARCHAR(12) NOT NULL PRIMARY KEY
,score INT NOT NULL
);
INSERT INTO results VALUES
('Anna',19),
('Jacob',47),
('Joe',50),
('Sarah',34);
*/
include('path/to/connection/stateme.nts');
$query = "
SELECT name, score FROM results ORDER BY score DESC;
";
$result = mysqli_query($conn,$query);
$i=1;
while($row = mysqli_fetch_assoc($result)){
echo $i." ".$row['name']." ".$row['score']."<br/>\n";
$i++;
};
?>

Related

Saving data from database into associative array with counting up - PHP

I would like to sort data from my database. I want to use associative arrays so it can be sorted the best.
I get all the data from a database, as said above. By doing $row['manufacturer'] I'll get some data like the following:
motorola
sony
motorola
google
samsung
lg
samsung
I would like it to be saved like this in the array: (order is not important, although alphabetically is preferred)
"motorola" => 2
"sony" => 1
"google" => 1
"samsung" => 2
"lg" => 1
I tried it by doing this, but it just didn't work and caused my web host to clean the logs, as it caused almost 2 gigs of log files.
The code I wrote to save it
$manufacturers = array();
//$row are the rows from my database. I will not add them, but by doing $row['manufacturer'] you'll get some brands like google, motorola, etc.
while($row = $resultSelect->fetch_assoc()) {
for ($i = 0; $i < $manufacturers; $i++) {
$alreadyEntered = 0;
if ($manufacturers[$i] == $row['manufacturer']) $alreadyEntered = 1;
if ($alreadyEntered == 0) {
$manufacturers[$row['manufacturer']] = 1;
} else {
$manufacturers[$row['manufacturer']] += 1;
}
//It caused huge logs, so I decided to break on 50.
if ($i > 50) {
break;
}
}
}
//Dump it :) to see if it worked
var_dump($manufacturers);
I have no idea how I can make it work. I tried searching on Google and SO for setting values in associative arrays, but nothing worked.
EDIT:
My rows:
You could do it through SQL query.
Using the count and group by query.
SELECT name, COUNT(*) as total
FROM manufactures
GROUP BY name
ORDER BY name ASC
name is your manufactures name column. manufactures is your table name.
Example PHP code:
$sql="SELECT name, COUNT(*) as total
FROM manufactures
GROUP BY name
ORDER BY name ASC";
$result=mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
{
echo "Name: ". $row['name'] . " Total: ". $row['total'] . "<br>";
}
Brief explanation:
What the query will do is that it will select all manufactures name, and count them. By in the same time, it will group together the names, which means, multiple same name will be grouped together, and counted together. Finally order by name asc is used to sort the result alphabetically in ascending order (A->Z).

SELECT * FROM table WHERE (value in cell as array) = $searchid [duplicate]

This question already has answers here:
How to regex in a MySQL query
(2 answers)
Closed 8 years ago.
I've got a db_table where some cells contain comma separated arrays to link them to all the corresponding rows in a different table column, like [846,1400,1657].
So how do i select all rows where that cell has one matching value in the array?
$result = "";
$searchid = $_POST['id'];
$query = mysql_query("SELECT * FROM Company WHERE City/*<-the array*/ LIKE '%$searchid%'");
$count = mysql_num_rows($query);
if($count == 0){
$result .= "no companies";
} else {
while($row = mysql_fetch_array($query)){
$name = $row['Name'];
$result .= "<div class=\"result\">$name </div>";
}
}
echo $result;
This gives all companies with $searchid, but if $searchid = 25, it will return the ones with 25 in that column as well as those with for example 250 and 725. :/
Without the wildcards tho:
$query = mysql_query("SELECT * FROM Company WHERE City/*<-the array*/ = '$searchid'");
will return the rows with only $searchid in that cell, for example if $searchid = 25 a cell with [25] and not one with [25,456] or [12,13,25]
I've goggled for 48 hours and tried everything i found, think this should be an easy one to crack.
What have i missed???
The FIND_IN_SET function might work for this one. Here's an example:
SELECT * FROM Company WHERE FIND_IN_SET('25', City) > 0
The example assumes that the City column is the one with the comma-separated list; I think that's what your question states.
You could try using the like statement :
SELECT * FROM Company WHERE City LIKE "%25%";
Obviously this would select ones with 250 in too but it's a start.
You can't do split in mysql, you should have used a transitional table :
city_company
------------
id_city
id_company
Where you could have stored all these relations.
Though you could use like for a quick dirty hack.
Here is how you could do it :
$query = mysql_query("SELECT * FROM Company WHERE concat(',',City,',') LIKE '%,$searchid,%'");

PHP Pagination-related MySQL query issue

I'm trying to do 2 things.
1) Get the amount of rows in this query
SELECT
COUNT(*)
FROM
`my_table`
WHERE
`column_1` = 152
AND
`column_2` = 42
ORDER BY
`column_3`
As you can see that is no problem ^^
2) Determine the number within the range of rows that is returned by id
Ex: ID 765 is Item 4 of 7 where column_1 = 152 and column_3 = 42
Does anyone have any basic solutions to this problem with almost pure MySQL? I'd like to avoid iterating through all the rows and setup a counter to increment until it matches current id like this:
$sql = '
SELECT
*
FROM
`my_table`
WHERE
`column_1` = 152
AND
`column_2` = 42
ORDER BY
`column_3`
';
$query = mysqli_query($sql);
$current_id = 2523;
$i = 1;
while ($row = mysqli_fetch_assoc($query)) {
if ($row['id'] == $current_id) {
$current_position = $i;
}
$i++;
}
print 'Current position in range is: '. $current_position;
Also please don't worry about the actual syntax, I won't be using this exact script, but you get the logic that I'd like to avoid using. If anyone has a better solution, please let me know. Thanks in advance!!

Total up how many men and how many women in a column. Possibly in order to repopulate the planet

Trying to search through a column in a db, and pull out the total number of males, and total number of females.
This data is stored in the db as f and m in the whatsex column.
$query = "SELECT whatsex, COUNT(*) FROM soberdata GROUP BY whatsex";
$result = mysqli_query($connection,$query) or die(mysql_error());
$sexdb = mysqli_fetch_array($result);
$totalmale = $sexdb['m'];
$totalfemale = $sexdb['f'];
echo $totalfemale." & ".$totalmale;
This code outputs nothing. What am I doing wrong?
$sexdb have only "whatsex" and "COUNT(*)" columns. You should use one of them
try
print_r($sexdb);
and look if some of results meet your needs
Your query is going to return a whatsex value, and a COUNT(*) value, not m or f. Doing a var_dump($sexdb) would show you what's in the array.
You are treating a multi-dimensional array as flat. You could do this to flatten it
$query = "SELECT whatsex, COUNT(*) as total FROM soberdata GROUP BY whatsex";
while ($row = mysqli_fetch_array($result)) {
$$row['whatsex'] = $row['total']; // this makes a variable ($m or $f) using the value of the row
}
$totalmale = !empty($m) ? $m : 0;
$totalfemale = !empty($f) ? $f : 0;
You should empty check the results of the db in case there is no male or female entries to avoid errors.

Why returns the first element of an array only?

$count =0;
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");
$result4= mysql_fetch_array($result3);
print $result4[$count].'<br>';
$count++;
}
mysql_free_result($result1);
mysql_free_result($result3);
Let's have a look at how mysql_fetch_array works - for example if you have table structure like
id | name | surname | role
1 John Smith user
2 Peter Qeep user
3 Mark Ziii admin
When you execute a query SELECT * FROM table and then loop $result = mysql_fetch_array($query), $result will always be an array(4) containing
[0] => id,
[1] => name,
[2] => surname,
[3] => role
Therefore, when you execute the query $result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2[$count]."'");, in the first iteration, $count will be 0 which is the key for the result returned by the previous query, however in any further iteration it will increase and that will lead to an undefined key. This means that you have to stop using the variable $count and just use $result2[0] instead.
Also, way better approach to this would be using MySQL JOIN, in your example it would be SELECT w.fsyn FROM sbsw s JOIN wrsyn w ON s.fwid = w.fwid WHERE s.fword = "'.$searchText.'";
Please, use reasonable variable names and indent properly. You're getting one column from each row as you're only printing out once for each iteration over your rows.
Basically: For each row, print the value of a column.
The $count-variable decided which column, but it obviously didn't make sense at it counts the row you're at.
Something like this should do it: (not tested)
$result1 = mysql_query("SELECT fwid FROM sbsw WHERE fword = '".$searchText."'");
while ($result2= mysql_fetch_array($result1))
{
$result3 = mysql_query("SELECT fsyn FROM wrsyn WHERE fwid = '".$result2['fwid']."'");
$result4= mysql_fetch_row($result3);
for($x = 0; $x < count($result4); $x++){
print $result4[$x].'<br>';
}
}
mysql_free_result($result1);
mysql_free_result($result3);
Oh and I changed fetch_array to fetch_row in the inner loop to ease iteration.

Categories