Let's Say I have Data...
ID... 1, 2, 3, 4, 5, 6
FirstName... Donald, Tabatha, Jeremy, Samuel, Donald, Tabatha
LastName... Faulknor, Kolasa, Jones, Jackson, Faulknor, Kolasa
In this example, I would want to display
Donald Faulknor, Tabatha Kolasa, Jeremy Jones, Samuel Jackson
I can either display all data (repeating the duplicate entries) or, if I use SELECT DISTINCT then I will only display the first instance, which in this case would be Donald Faulknor. Here's my code...
$sql55 = "SELECT * FROM messages WHERE lowerID = :lowerIDb || higherID = :higherIDb";
$stmt55 = $pdo->prepare($sql55);
$stmt55->bindValue(':lowerIDb',$user_id);
$stmt55->bindValue(':higherIDb',$user_id);
$stmt55->execute();
while($row55 = $stmt55->fetch(PDO::FETCH_ASSOC)) {
$lowerID55 = $row55['lowerID'];
$higherID55 = $row55['higherID'];
if($lowerID55 == $user_id) { $user_id55 = $higherID55; } elseif($higherID55 == $user_id) { $user_id55 = $lowerID55; }
$sql56 = "SELECT DISTINCT user_id FROM users WHERE user_id = :user_id55";
$stmt56 = $pdo->prepare($sql56);
$stmt56->bindValue(':user_id55',$user_id55);
$stmt56->execute();
while($row56 = $stmt56->fetch(PDO::FETCH_ASSOC)) {
$id56 = $row56['user_id'];
$sql58 = "SELECT * FROM users WHERE user_id = :user_id58";
$stmt58 = $pdo->prepare($sql58);
$stmt58->bindValue(':user_id58',$id56);
$stmt58->execute();
while($row58 = $stmt58->fetch(PDO::FETCH_ASSOC)) {
$firstname56 = $row58['firstname'];
$lastname56 = $row58['lastname'];
$profilePhoto56 = $row58['profilePhoto'];
$sql57 = "SELECT * from photos WHERE id = :profilePhotoa";
$stmt57 = $pdo->prepare($sql57);
$stmt57->bindValue(':profilePhotoa',$profilePhoto56);
$stmt57->execute();
while($row57 = $stmt57->fetch(PDO::FETCH_ASSOC)) {
$profilePhotoPath57 = $row57['path'];
echo '';
echo ' '.$firstname56.' '.$lastname56.'';
}
}
}}
To better understand the above code... I have messages to and from users, of course, there will be many to and from the same users. I'm trying to get their name (the recipient) to show once in a side bar (indicating messages from/to that person. Let's say for example, I have 20 messages to and from one person. I can either get the name to repeat twenty times (not using DISTINCT) or I can only get one person's name to show (using DISTINCT). So if there's 8 people to send this user an email, only one name will show.
Much help is greatly appreciated. For questions or more elaboration, please feel free to ask questions. Thank You! :)
Related
I am new to php so far i wrote this referral script:
<?php
ob_start();
include( $_SERVER['DOCUMENT_ROOT'] . '/config.php' );
mysql_connect(DB_HOST,DB_USER,DB_PASS);
mysql_select_db(DB_NAME);
$id = $_REQUEST['id'];
$uid = $_REQUEST['uid'];
$oid = $_REQUEST['oid'];
$new = $_REQUEST['new'];
$total = $_REQUEST['total'];
$sig = $_REQUEST['sig'];
// Secrete Key
$hash = 'myapikey';
// Output results
if ($sig == $hash) {
//Users point update query here (it's working )
$users = mysql_query("SELECT points FROM users WHERE id=".$uid);
$rows = mysql_fetch_array($users);
$user_points = $rows['points'];
$query1 = mysql_query("update users set points=($user_points+$new) where id=".$uid );
//Updating referral coins (it's not working )
$query2 = ("SELECT points, referral_id, level FROM users WHERE referral_id=".$uid );
$user_rows = mysql_query($query2);
$all=mysql_fetch_array($user_rows,MYSQL_BOTH);
if($all['referral_id'] != 0 && $all['level'] == 0){
$lvl0 = $new*(15/100);
$referal_points = $lvl0;
$update_referral_points = ("update users set points = points + $referal_points where referral_id = ".$all['referral_id']);
mysql_query($update_referral_points);
} else if($all['referral_id'] != 0 && $all['level'] == 1){
$lvl1 = $new*(25/100);
$referal_points = $lvl1;
$update_referral_points = ("update users set points = points + $referal_points where referral_id = ".$all['referral_id']);
mysql_query($update_referral_points);
}
print "1\n";
} else {
print "0\n";
}
?>
How Script working:
whenever someone signup using referral code i have insert referral code user id into new user referral_id row, & through $_REQUEST['']; my app sending points ($new) to user...
$query1 is working fine there's problem to execute $query2, in short $query2 needs to be fixed; something getting wrong, that i am not able to figure out if any pro can help me out this i will appreciate it...
DB structure:
users table:
id (AI) name points Referral code Referral id Level
=========== ========== ========== ================== ============== ======
1 user A 0 abcdef123 0 0
2 user B 100 bvsuda897 1 1
3 user C 500 vrtasio65 2 0
In this example above,
1- user C signup using user B Referral code = bvsuda897
2- right now user B level is 1 so whenever user C earn point ($new) my app should give user B 25% coins of user C $new
The Problem
right now when my app sending coins to user C, user B not getting coins, because something wrong in query2
After spending some more time looking over your code, I have tracked down your issue. First, you need to get the referral_id from the $users query.
$users = mysql_query("SELECT points, referral_id FROM users WHERE id=".$uid);
Then $query2 needs to match the id to the user's referral_id, not the other way around.
$query2 = "SELECT id, points, referral_id, level FROM users WHERE id=".$rows['referral_id'];
Your UPDATE queries may need some work after that, but this will get you in to the if else conditions.
Successful code determined by OP
//Updating referral coins
$query2 = "SELECT id, points, referral_id, level FROM users WHERE id=".$rows['referral_id']; $user_rows = mysql_query($query2);
$all=mysql_fetch_array($user_rows,MYSQL_BOTH);
$lvl0 = intval((5/100) * $new);
$lvl1 = intval((10/100) * $new);
$query3 = mysql_query("update users set points = (points + $lvl0) where level = 0 AND referral_id = ".$all['referral_id']);
$query4 = mysql_query("update users set points = (points + $lvl1) where level = 1 AND referral_id = ".$all['referral_id']);
Now I appreciate that you are in the learning stage, but I want to point out a couple things that will cause confusions as you pursue PHP programming in the future.
First off, as Option mentioned, the MySQL functions you are using have been deprecated. They do not exist in the current stable version of PHP, and your code will no longer work if the server is updated. Look in to MySQLi or PDO as alternatives. It's a lot to learn, but some Googling will get you some guidance.
Second is your use of $_REQUEST, which combines the values of $_GET, $_POST and $_COOKIE, allowing easy manipulation by visitors. It may be that you are only using it for the user details while testing your other code, but I just want to make sure you know about PHP sessions, which is the better way to store a relationship between a logged in user and their persistent variables.
So i have a 3 tables. A match table with records of the two teams playing against each other.
mchID mchTeama mchTeamb mchScorea mchScoreb
1 Cathedral Holy Trinity 3 0
2 St. Andrew's Immanuel
Church 2 0
I also have teams table with records of all teams participating
tmID tmName
1 Cathedral
2 Holy Trinity Lekki
and the players table
plyID plyName plyPosition teamID
1 Michael Defense 2
2 Peter Forward 1
3 Chukwudi Forward 1
4 Johnson Midfield 2
5 John Forward 2
6 Samuel keeper 1
On my html page, i have a form with multiple drop downs that gets populated from the players table based on a series of queries to all three tables based on the match ID passed to the page.
$colname_matchrf = "-1";
if (isset($_GET['mchrf'])) {
$colname_matchrf = $_GET['mchrf'];
}
$query_match = "SELECT * FROM matches WHERE mchID = $colname_matchrf";
$result_match = mysqli_query($connBiscup, $query_match);
$row_match = mysqli_fetch_assoc($result_match);
$totalRows_match = mysqli_num_rows($result_match);
$matchTeamA = $row_match['mchTeama'];
$matchTeamB = $row_match['mchTeamb'];
$query_lineupteama = "SELECT * FROM teams WHERE tmName = '".$matchTeamA. "'";
$result_lineupteama = mysqli_query($connBiscup, $query_lineupteama);
$row_lineupteama = mysqli_fetch_assoc($result_lineupteama);
$totalRows_lineupteama = mysqli_num_rows($result_lineupteama);
$matchTeamaID = $row_lineupteama['tmID'];
$query_playersa = "SELECT * FROM players WHERE teamID = $matchTeamaID AND plyPosition != 'Coach' AND plyPosition != 'Assistant Coach'";
$result_playersa = mysqli_query($connBiscup, $query_playersa);
$row_playersa = mysqli_fetch_assoc($result_playersa);
$totalRows_playersa = mysqli_num_rows($result_playersa);
$query_lineupteamb = "SELECT * FROM teams WHERE tmName = '".$matchTeamB. "'";
$result_lineupteamb = mysqli_query($connBiscup, $query_lineupteamb);
$row_lineupteamb = mysqli_fetch_assoc($result_lineupteamb);
$totalRows_lineupteamb = mysqli_num_rows($result_lineupteamb);
$matchTeambID = $row_lineupteamb['tmID'];
$query_playersb = "SELECT * FROM players WHERE teamID = $matchTeambID AND plyPosition != 'Coach' AND plyPosition != 'Assistant Coach'";
$result_playersb = mysqli_query($connBiscup, $query_playersb);
$row_playersb = mysqli_fetch_assoc($result_playersb);
$totalRows_playersb = mysqli_num_rows($result_playersb);
This is the form drop down sample
<?php
while ($row_playersa = mysqli_fetch_assoc($result_playersa)) {
$playersa[] = $row_playersa;
}
?>
<div class="std_textbox2">
<select name="captaina" class="input-field-login3" id="captaina" tabindex="1">
<option selected="Selected">--Select Player--</option>
<?php foreach ($playersa as $playera): ?>
<option value="<?php echo $playera['plyName']; ?>"><?php echo $playera['plyName']; ?></option>
<?php endforeach ?>
</select>
</div>
So the issue is this, the forms drop down gets populated but not with all the records I expect to be there. For instance the drop down for the team A should have all players from the players table who have their teamID as 1. But what I get is just some of the records not all.
Any help as to whats wrong would be highly appreciated.
You want to use AND in your where statement not &&, && does something else.
$query_playersa = "SELECT * FROM players WHERE teamID = $matchTeamaID and plyPosition != 'Coach' and plyPosition != 'Assistant Coach'";
also change your code to not be vulnerable to injection attacks. Your site will be powned in hours.
Thanks everyone for your help. I have found the issue. In the sql query, I have already called this method $row_playersa = mysqli_fetch_assoc($result_playersa); this has already taken the first row. So calling up that method again in the loop while ($row_playersa = mysqli_fetch_assoc($result_playersa)) {
$playersa[] = $row_playersa;
} takes up the second record and so on. So to solve the issue, i took out the method in the query itself.
Before I show what I have tried, i'll just explain my scenario. I have three tables. Genre, Games, GameGenre.
Genre = The different game genres (Action, Adventure, Multiplayer)
Games = The different games (example 1, example 2, example 3)
GameGenre = the grid and the gaID and also the ggID (genre, game and gamegenreID)
Currently how this works is, firstly you would create a game genre, then add specific games to that genre. So they both have a geID and a gaID.
Now, what I am trying to do is display these according to genre. So that when I choose a genre, only games which have that genre are listed. Hence I have the ggID.
Code:
mysql_query("SELECT * FROM Genre WHERE gaID == geID = '$ggID'");
while($row = mysql_fetch_array($results)){
$geID = $row['geID'];
$gaID = $row['gaID'];
echo statements here.
}
This does not work though, any help please?
Did you tried this ?
mysql_query("SELECT * FROM Genre WHERE gaID = '$ggID' AND geID = '$ggID'");
Try
mysql_query("SELECT * FROM Genre WHERE gaID = geID AND geID = '$ggID'");
SQL is not C++, and = is not an assignment operator, so A = B = C doesn't make sense. And there is not == in SQL.
I have 2 variables which both hold comma separated lists. One is a permissions variable and the other is the usergroup list of the person wanting to access a page.
1 = user
2 = editor
3 = moderator
4 = admin
<?php
$query = mysql_query("SELECT * FROM users WHERE id='{$user['id']}'");
$user = mysql_fetch_assoc($query);
$query2 = mysql_query("SELECT * FROM menu WHERE active='1'");
$page = mysql_fetch_assoc($query2);
echo $user['usergroup']; // 1
echo $page['usergroup']; // 2,3,4
?>
I need help to find a way to compare both variables to check if they have the right usergroup to access a page
if $user['usergroup'] contains a number from $page['usergroup'] do X otherwise do Y
Thanks :)
$user = "1,3,5";
$page = "1,2,5";
//explode and trim for a case you have spaces '1, 2,3 ,4'
$u = array_map('trim', explode(",", $user));
$p = array_map('trim', explode(",", $page));
$intersect = array_intersect( $u, $p );
if ( count($intersect) )
{
//ok
print_r( $intersect );
}
else
{
//error
}
Allowed permissions:
Array
(
[0] => 1
[2] => 5
)
Try this:
$query = mysql_query("SELECT * FROM users WHERE id='{$user['id']}'");
$user = mysql_fetch_assoc($query);
$query2 = mysql_query("SELECT * FROM menu WHERE active='1'");
$page = mysql_fetch_assoc($query2);
$pageGroups = explode(',', $page['usergroup']);
if (array_search($user['usergroup'], $pageGroups) !== false) {
//TODO: User have access
}
Although I wouldn't store permissions as a commaseparated string, something like this might be what you are looking for:
$pageaccess = explode(',', $page['usergroup']);
if(in_array($user['usergroup'], $pageaccess)) {
// Has permissions. Code goes here.
}
edit: renamed $permissions to $pageaccess
While all the answers you got should work I'd like to add a comment to your approach. It's never a good idea to store comma seperated lists into your database. It offends the concept of database normalization.
Instead of storing comma seperated lists you should reconsider your database design. A possible approach could be:
users (user_id, username)
permissions(permission_id, permission)
user_permissions(up_id, permission_id, user_id)
That is much more efficient since you don't need to process the data that come from your database any further. You can just query your database and ask if the user has a certain permission.
SELECT `up_id` FROM `user_permissions` WHERE `user_id` = '{$uid}' AND `permission_id` = {5}
Taking this a step further you can assemble a little access control list:
users (user_id, username)
groups (group_id, name)
user_groups(ug_id, group_id, user_id)
permissions(permission_id, permission)
group_permissions(gp_id, group_id, permission_id)
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