Stuck with the same values when looping through database rows - php

I am trying to make a function where the following should happen:
Retrieve the ID value of all users in database.
Retrieve all numbers belonging to each user from an other table in the same database.
Add all the numbers belonging to each user together.
By using my code (see below), step 1 and 3 is working. At step 2, it is looping the correct amount of times but in every loop it retrieves the numbers belonging to the first ID from step 1.
Example:
Step 1 finds the following IDs: 1, 2, 3 and 4.
Step 2 loops 4 times, but retrieves the numbers belonging to ID 1 every time instead of retrieving the numbers to ID 1 in the first loop, ID 2 in the second etc.
My PHP:
$users_get = mysqli_query($conn,"SELECT id FROM users");
$users_num = mysqli_num_rows($users_get);
$users_list = array();
while($users_row = mysqli_fetch_array($users_get)){
$users_list[] = $users_row;
}
foreach($users_list as $users_row){
$users_items[] = array(
'id' => $users_row['id']
);
}
for($loop1 = 0; $loop1 < $users_num; $loop1++){
$numbers_get = mysqli_query($conn,"SELECT number FROM users_numbers WHERE userid = '".$users_items[$loop1]['id']."'");
$numbers_num = mysqli_num_rows($numbers_get);
$numbers_list = array();
while($numbers_row = mysqli_fetch_array($numbers_get)){
$numbers_list[] = $numbers_row;
}
foreach($numbers_list as $numbers_row){
$numbers_items[] = array(
'number' => $numbers_row['number']
);
}
$numbers_added = 0;
for($loop2 = 0; $loop2 < $numbers_num; $loop2++){
$numbers_added = $numbers_added + $numbers_items[$loop2]['number'];
}
}
I later added som echos to display the IDs and numbers that is retrieved and got the following result:
User ID: 1
Amount of numbers: 4
Numbers:
4 (Belonging to ID 1)
7 (Belonging to ID 1)
5 (Belonging to ID 1)
2 (Belonging to ID 1)
Total: 18
User ID: 2
Amount of numbers: 0
User ID: 3
Amount of numbers: 3
Numbers:
4 (Belonging to ID 1)
7 (Belonging to ID 1)
5 (Belonging to ID 1)
Total: 16
The amount of numbers for ID 3 is correct, however the 3 retrieved numbers belongs to ID 1.
Another observation I made was if I edit the SELECT query inside loop 1:
"SELECT number FROM users_numbers WHERE userid = '".$users_items[$loop1]['id']."'"
And manually selects an ID, example:
"SELECT number FROM users_numbers WHERE userid = '3'"
Then it retrieves the correct numbers belonging to ID 3.
After hours of trying to figure out what I'm doing wrong I still haven't found anything, so any help is really appreciated! Is there something I can do with my current code to fix it, or maybe there is some other ways to achieve the desired function?

Based on the comments on my question, I ended up with the following code:
$users_get = mysqli_query($conn,"SELECT a.id, SUM(b.number) AS number FROM users AS a INNER JOIN users_numbers AS b ON a.id = b.userid GROUP BY a.id ASC");
$loop1 = 0;
while($users_items[] = mysqli_fetch_array($users_get){
echo "ID: ".$users_items[$loop1]['id']." - Num total: ".$users_items[$loop1]['number']."<br />";
$loop1++;
}
The echo inside the while is only for testing purposes. When I run this, it displays a nice list with all the user IDs and the sum of each users numbers.

Related

Displaying the users according to the position in the database

I have a database with multiple users. Each user has an id, name and position. I want to display users by position. To take an example I have a table with 7 numbered positions.
Position Name
1.
2.
3.
4.
5.
6.
7.
And 4 users in the database that I want to display according to their position.
Name Position
User_1 4
User_2 7
User_3 1
User_4 3
How can I do this without using the loop for or while for display?
I tried
for ($j=1; $j<=$no_rows; $j++){
$rand = mysqli_fetch_array($tabel);
$name[$j]=trim($rand['user']);
}
And then display for each number in that table that name[j].
Position Name
1. $name[1]
2. $name[2]
3. $name[3]
4. $name[4]
5. $name[5]
6. $name[6]
7. $name[7]
If those 4 users have positions 1,2,3,4, they are arranged by position, if one has the position higher than the total number of users then nothing is displayed, or it is displayed chaotically.
I also tried with j <= 7 but again the same problem.
The question needs more info but here is a rough idea based on what you have so far and my making some assumptions that this is a leader board style list.
// Something like: $query = 'SELECT * FROM users ORDER BY point DESC';
$count = 1;
while ($row = mysqli_fetch_array($query_results_object))
{
// Process data here.
echo $count . ': ' . $row['username'];
// Bail on 7.
if ($count >= 7)
{
break;
}
$count ++;
}
// Fill in empty values.
while ($count < 7)
{
echo $count . ': Space available.';
}
You did say without using the loop for display and your modified example appears to indicate you want rank instead of leader board position.
// Something like: $query = 'SELECT * FROM users';
$list = array_fill(1, 7, 'empty_value');
while ($row = mysqli_fetch_array($query_results_object))
{
// Process data here.
$list[$row['rank']] = $row['name'];
}
echo $list[1];
echo $list[2]];
...
This would be very inefficient as if you had 100 users you would be adding all of them to an in-memory table only to display 7 of them. So make sure you query does something like: SELECT TOP 7 * FROM users ORDER BY position DESC

MYSQL / PHP Calculating number of occurrences

First off all I am slightly confused what the best implemtentation would be for the following problem i.e pure can it be done with only mysql without altering tables or would I need a combination of PHP and mysql as I am currently doing.
Please keep that in mind as you read on:
Question Info
A Pickem game works as follow:
1- Display all matches / fixtures in a round for a tournament.
2- User enters which teams he thinks will win each fixture.
The fixtures are pulled from a table schedule and the users results are recorded in a table picks
Keep In mind
Each round can have a number of matches (anywhere between 1 to 30+ matches)
What I am trying todo / PROBLEM
I am trying to calculate how many users selected team1 to win and how many users selected team2 to win for a given round in a tournament.
Example
Manchester United: 7 users picked |
Arsenal 3: users picked
MYSQL TABLES
schedule table Schedule of upcoming games
picks table User Picks are recorded in this table
Expected Output From Above Tables After Calculations
So for Super Rugby Round 1 it should read as follow:
gameID 1 4 picks recorded, 2 users selected Jaquares 1 user Selected Stormers (ignore draw fro now)
gameID 2 4 picks recorded, 4 users selected Sharks, 0 users selected Lions
My Code
function calcStats($tournament, $week)
{
global $db;
//GET ALL GAMES IN TOURNAMENT ROUND
$sql = 'SELECT * FROMpicks
WHERE picks.tournament = :tournament AND picks.weekNum = :weekNum ORDER BY gameID';
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':tournament', $tournament);
$stmnt->bindValue(':weekNum', $week);
$stmnt->execute();
if ($stmnt->rowCount() > 0) {
$picks = $stmnt->fetchAll();
return $picks;
}
return false;
}
test.php
$picks = calcStats('Super Rugby', '1');
foreach($picks as $index=> $pick) {
if($pick['gameID'] !== $newGameID){
?>
<h1><?php echo $pick['gameID']?></h1>
<?php
//reset counter on new match
$team1 = 0;
$team2 = 0;
}
if($pick['picked'] === $newPick){
//gameID is passed as arrayKey to map array index to game ID
//team name
$team1[$pick['picked']];
//number times selected
$team1Selections[$pick['gameID']] = $team1++;
}
else if($pick['picked'] !== $newPick){
///gameID is passed as arrayKey to map array index to game ID
//team name
$team2[$pick['picked']];
$team2Selections[$pick['gameID']] = $team2++;
}
$newPick = $pick['picked'];
$newGameID = $pick['gameID'];
}
PRINT_R() Of function $picks = calcStats('Super Rugby', '1')
I hoe my question makes sense, if you need any additional information please comment below, thank you for taking the time to read.
It seems that you're doing too much within PHP that can be easily done within MySQL; consider the following query:
SELECT gameID, team, COUNT(*) AS number_of_picks
FROM picks
WHERE picks.tournament = :tournament AND picks.weekNum = :weekNum
GROUP BY gameID, team
ORDER BY gameID, team
This will give the following results, given your example:
1 | Jaquares | 2
1 | Stormers | 1
1 | Draw | 1
2 | Sharks | 4
Then, within PHP, you perform grouping on the game:
$result = array();
foreach ($stmnt->fetchAll() as $row) {
$result[$row['gameID']][] = $row;
}
return $result;
Your array will then contain something like:
[
'1' => [
[
'gameID' => 1,
'team' => 'Jaquares',
'number_of_picks' => 2,
],
'gameID' => 1,
'team' => 'Stormers',
'number_of_picks' => 1,
],
...

Determine the next number in database query with while loop in php

I have a Part Management system I've created in PHP with MySQL. What I'm trying to create is something that will generate the next Part Number for me. All part numbers start with a 3 letter prefix (which is determined by the product family/category) followed by their number.
For example 'ABC001'
What I have below is something that I'd like to use to determine what the next number is having already 'ABC001', 'ABC002' & 'ABC003' so I would like it to recognize what the next number is by querying until the query comes back false because that product number doesn't exist yet.
$abc_query = "SELECT * FROM products WHERE id LIKE 'ABC%'";
$abc_result = $mysqli2->query($abc_query);
while($row = $abc_result->fetch_assoc()) {
$rowid = $row["id"];
$pnumber = substr($rowid, 3, 3);
echo $pnumber. '<br/>';
$int = (int)$pnumber;
$abc_query2 = "SELECT * FROM products WHERE id 'ABC" . sprintf('%03s', $int);
for ($abc_query2 = true; $abc_query2 = false; $int++){
echo $int;
}$abc_nextnumber = $int +1;
}
$abc_newnumber = 'ABC' . sprintf('%03s', $abc_nextnumber);
echo $abc_newnumber;
The result I get is
001
002
003
005
ABC006
However the result should be..
001
002
003
ABC004
code update I've updated the code but it doesn't seem to stop at ABC004 if I have an 005. It will go to 006.
You should have the db do this instead of your app:
select t.id_prfx, max(t.id_num) as latest_num from
(select substring(id, 1, 3) as id_prfx,
cast(substring(id,4) as integer) as id_num) t
group by id_prfx
This will give you a result table where you get the highest part number for each prefix.
If you really really only want prefixes of 'ABC' then:
select max(cast(substring(id,4) as integer)) as max_num from table
where id LIKE 'ABC%'
Could you try this query?
SELECT MAX(SUBSTR(id, 4)) as last_id FROM products WHERE SUBSTR(id, 1, 3)='ABC'
EDİT:
products TABLE
==============
ABC001
ABC002
ABC003
ABC005
==============
We want to find 4 in products table.
SELECT SUBSTR(t1.id, 4) + 1 as POSSIBLE_MIN_ID
FROM products t1
WHERE NOT EXISTS (
SELECT *
FROM products t2
WHERE SUBSTR(id, 1, 3)='ABC' AND SUBSTR(t2.id, 4) = SUBSTR(t1.id, 4) + 1
) LIMIT 1
RESULT:
POSSIBLE_MIN_ID : 4
If anyone knows how I can have it add automatic zeros to the into the query (as it will be different amount of 0s once it gets to 'ABC011') instead of typing them in that would also be very helpful.
Here's how to automatically handle the prepended zeroes.
$sql3 = "SELECT * FROM products WHERE id 'ABC" . sprintf('%03s', $int);

Creating an array for users and their ratings

I'm having a problem in getting an array of a users ratings. The scenario is, I have a function that compares two arrays of numbers, and calculates how similar they are using cosine similarity.
I want to use this, to calculate the similarity of ratings from one user, to x number of other users in the database, finding the user with the most similar ratings.
The two tables relevant to this are films and ratings. Rows relevant for Film are filmID, and ratings has rows filmID, userID, and rating. for example:
filmId userID rating
1 1 3
1 3 4
2 1 2
3 1 2
2 3 3
So for user 1, I'd want an array $user1[3, 2, 2] and for user 3 $user3[4, 3, 0]
Notice that in the array for user 3, the film they HAVEN'T rated is now a zero. These arrays will then be passed to the function to calculate similarity.
I don't know how to get the user arrays from the tables I have. I wrote some code, but am fairly stumped. So far I have:
$users = mysql_query("SELECT * FROM user");
$ratings = mysql_query("SELECT * FROM ratings");
while ($userRow = mysql_fetch_assoc($users)) {
$similarCheck = mysql_query("SELECT * FROM ratings WHERE userID =".$userRow['userID']);
$similarArray = mysql_fetch_assoc($similarCheck);
$count = 0;
while ($similarArray = mysql_fetch_assoc($similarCheck)){
$count++;
}
for ($i=0; $i < $count; $i++){
$user1 = array();
$user1[$i] = $similarArray['rating'];
}
}
Thanks for any help I do receive. If you require any further information, please let me know.
You're not actually doing anything with your query:
while ($similarArray = mysql_fetch_assoc($similarCheck)){
$count++;
}
This code simply loops through the query results and assigns each row to a variable, which is then overwritten over and over. When the loop exits, you'll have a FALSE value assigned to $similarArray, since mysql_fetch calls return a boolean false when there's no more results.
You then try to use this boolean false value in ANOTHER loop as an array which will throw all sorts of warnings.
Most likely you want something like this:
$similarCheck = mysql_query("SELECT * FROM ratings WHERE userID =".$userRow['userID']) or die(mysql_error());
$similarArray = array();
while($row = mysql_fetch_assoc($similarcheck)) {
$similarArray[] = $row['rating'];
}

Php lottery issues multi winner problems

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

Categories