I have 2 tables
USERS
------------
id | user
1 | john
2 | George
3 | Andy
Text
--------------------------------
id | user |date |text
1 | 1 |2012/10/2 | ABC
2 | 3 |2012/11/2 | ABCD
3 | 2 |2012/12/2 | ABCDE
4 | 2 |2012/1/2 | ABCDE
In the Text table the user column gets the id from the Users table.
I have the following query:
$sql= mysql_query ("SELECT
user.id,
users.user,
CASE
WHEN text.date = CURDATE() THEN '1'
ELSE '0'
END AS 'today',
text.date,
text.text
FROM users user, text text
WHERE users.id = text.user;");
if (mysql_num_rows($sql)<=0)
echo "NO ENTRIES FOUND";
while ($row = mysql_fetch_assoc($sql))
{
$user =$row['user'];
$id =$row['id'];
$date2 =$row['date'];
if ($row['today'] == 1) { echo"
<div class='z'><a href='viewuser.php?id=$user'>$user</a></div><br>
"; } else { echo"
<div class='zx'><a href='viewuser.php?id=$user'>$user</a></div><br>
"; };
}
My question is:
How can I display the users whose date is equal with today's date, the first div(zx), and if not with the second div(z), comparing from 2 tables and display once if is it 2 times the user.
<!-- language: lang-sql -->
SELECT
u.id,
u.user,
CASE
WHEN t.date = CURDATE() THEN '1'
ELSE '0'
END AS 'today',
t.date,
t.text
FROM users u, text t
WHERE u.id = t.user;
Now to display the results just say
if ($row['today'] == 0) { class="zx"; } else { class="z"; }
Code is abbreviated, let me know if you need it detailed out.
Here is your updated code with my solution from above:
$sql = mysql_query ("
SELECT
u.id,
u.user,
CASE
WHEN MAX(t.date) = CURDATE() THEN '1'
ELSE '0'
END AS 'today'
FROM users u, text t
WHERE u.id = t.user
GROUP BY u.id, u.user");
if (mysql_num_rows($sql) <= 0)
echo "NO ENTRIES FOUND";
while ($row = mysql_fetch_assoc($sql))
{
$user =$row['user'];
$id =$row['id'];
if ($row['today'] == 1) {
echo "<div class='zx'><a href='viewuser.php?id=$id'>$user</a></div><br>";
} else {
echo "<div class='z'><a href='viewuser.php?id=$id'>$user</a></div><br>";
}
}
Related
My tables are as follows:
person2: personID
validPositions: positionID, positionDesc
personPositions: personID, positionID
I want to be able to display a person with their multiple positions (some may only have one position) on one line. Example: Sierra's Positions: s1, s2
Currently it displays each position they have, however on different lines AND it repeats the last position in the database twice. Example:
Sierra's Positions: S1
Sierra's Positions: S2
Sierra's Positions: S2
$sql = "SELECT * FROM person2";
// LEFT JOIN validTitles ON personTitle.positionID=validTitles.positionID GROUP BY person2.personID";
if ($result = mysqli_query($connection, $sql)) {
// loop through the data
//create 4 columns for the table
$columns=5;
$i = 0;
while($row = mysqli_fetch_array($result))
{
// the % operator gives the remainder of a division of two values
// in this case, 0/4, this tells the table row to jump to a new row
// if there are already 4 columns in one row
if($i % $columns == 0){
//begin table row
echo "<tr>";
} //end if
echo '<td class="staffImage badgeText frameImage displayInLine">
<br>
<strong>'.$row["firstName"].'</strong>
<strong>'.$row["lastName"].'</strong><br>'
.$row["position"].
'<div id="openModal'.$row["personID"].'" class="modalDialog">
<div>
X
<h2>' . $row["firstName"] . " " .
$row["lastName"].'</h2><br>
<img class="floatLeft" src="images/staff/'.$row["imgName"] .'.jpg">
<p><strong>Hire Date: </strong>'.$row["hireDate"].'<br>
<p><strong>Major: </strong>'.$row["major"].'<br>';
//if the field "major2" (Double Major) is not null, display it
if($row["major2"] != NULL)
{
echo ' & '.$row["major2"].'<br>';
}
//if the field "minor" is not null, display it
if($row["minor"] != NULL)
{
echo '<p><strong>Minor: </strong>'.$row["minor"].'<br>';
}
//if the field "concentration" is not null, display it
if($row["concentration"] != NULL)
{
echo '<p><strong>Concentration: </strong>'.$row["concentration"];
}
**$sql2 = "SELECT * FROM personPositions LEFT JOIN validPositions ON personPositions.positionID=validPositions.positionID ";
if ($result2 = mysqli_query($connection, $sql2)) {
// loop through the data
while($row2 = mysqli_fetch_array($result2))
{
echo '<p><strong>Position(s): </strong>'.$row2["positionDesc"];
}//end second while**
} //end second if
'</div>
</div>
</div> ';
echo '</td>';
Any help is greatly appreciated, I am new to PHP and MySQL and unsure what to do!
SAMPLE DATA:
personPositions table:
personID 1 | positionID 11
personID 1 | positionID 22
personID 2 | positionID 22
personID 2 | positionID 55
validPositions table:
positionID 11 | positionDesc S1
positionID 22 | positionDesc S2
positionID 55 | positionDesc S3
Something like this should work for you:
SELECT p.personID, GROUP_CONCAT(DISTINCT positionDesc ORDER BY positionDesc) AS positions
FROM person AS p
LEFT JOIN personPositions AS pp ON p.personID = pp.personID
LEFT JOIN validPositions AS vp ON pp.positionID = vp.positionID
GROUP BY p.personID
Output:
personID | positions
----------+-----------
1 | S1,S2
2 | S2,S3
Demo here
I have problem with selecting selecting SQL Max and group syntax then set it to variable. I have no problem from just selecting the MAX score. But Id like to echo the user that own that score and id to redirect to his profile page
This is my Database
-----------------------------
id | user | score | justplayed
1 | player1 | 1000 | 1
2 | player2 | 1000 | 0
PHP code
$sql = "SELECT MAX(score) AS max_score FROM score GROUP BY score WHERE justplayed > 0 ";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$highscore = $row["max_score"];
$highscoreowner = $row["user"];
$highscoreownerid = $row["id"];
}
}
Html Code
Player of the day
<? echo $highscoreowner; ?>
Score
<? echo $highscore; ?><br>
<a href="profile.php?id=<? echo $highscoreownerid; ?>
You're only selecting the max score in the SQL query, so you can't extract the other values in PHP. If you're looking for the entire row where the score is highest, then use this query instead:
SELECT score, user, id
FROM score
WHERE justplayed > 0
ORDER BY score DESC
LIMIT 1
This will take all the rows, order them from highest to lowest score, and then return only the first row.
functions.php
function getfriendone($id, $field){
$query = mysql_query("SELECT `$field` FROM `friends` WHERE `user_one`='$id'");
$run = mysql_fetch_array($query);
return $run[$field];
}
function getfriendtwo($id, $field){
$query = mysql_query("SELECT `$field` FROM `friends` WHERE `user_two`='$id'");
$run = mysql_fetch_array($query);
return $run[$field];
}
index.php
$fetch_friends = $_SESSION['user_id'];
$two = getfriendone($fetch_friends, 'user_two');
$three = getfriendtwo($fetch_friends, 'user_one');
$result = mysql_query("SELECT * FROM posts WHERE id IN ('$two', '$three')");
echo $two." | ".$three;
Table (friends) for getfriend function
ID user_one user_two
1 1 2
2 1 3
3 4 1
Table (posts) for $result
ID TEXT NAME
1 Hello Bob
1 Hello Bob
2 Hello Mark
What i wanna do here is echo all the rows that has integer 1 in it in both user_one and user_two. In my chase, only ID 1 and 3 will be echoed here. It picks the first match and echos only that one. It works as it should, but only with the first match in the column
If i read properly:
SELECT *
FROM posts s
WHERE
EXISTS
(SELECT 1 FROM posts s2 WHERE s.id = s2.user_one) OR
(SELECT 1 FROM posts s2 WHERE s.id = s2.user_two)
Will extract the data you need
SQLFiddle -> http://sqlfiddle.com/#!2/9ae070/3/0
This is how my table looks like:
id | name | value
-----------------
1 | user1| 1
2 | user2| 1
3 | user3| 3
4 | user4| 8
5 | user5| 6
6 | user7| 4
7 | user8| 9
8 | user9| 2
What I want to do is to select all the other users, in one query, who's value is user1's value lower than it's value plus 3, higher than it's value minus 3 or equal to it's value.
Something like this:
$result = mysqli_query($con,"SELECT * FROM users WHERE value<'4' OR value>'-2'") or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result))
{
echo $row['name'].'<br/>';
}
The problem is that users1's value can vary every time the query is run.
Sorry for lame names, but this should work:
NOTE: I named table with your data as "st".
SELECT b.user, a.value as "user1val", b.value as "otheruservalue" FROM st as a
join st as b
on a.user = "user1" and a.user != b.user
where
(b.value > (a.value - 3)) and (b.value < (a.value + 3))
We get unique pairs of user1's value and other user's value by joining same table. After that we just do some simple comparison to filter rows with suitable values.
$user1 = mysql_fetch_assoc(mysql_query("SELECT `value` FROM `users` WHERE id='1'"));
$result = mysql_query("SELECT * FROM `users` WHERE value<'".$user1['value']."+3' OR value>'".$user1['value']."-3'");
Or nested queries :
$result = mysqli_query($con, "select * from `users` where `value` < (select `value` from `users` where `name`='user1')+3 OR `value` > (select `value` from `users` where `name`='user1')-3");
I have table:
user_id | song_id| points
--------|----------------
2 | 1 | 0
2 | 2 | 1
2 | 3 | 2
2 | 4 | 3
2 | 5 | 4
And I need to check if the user have changed the points value.
Therefore it should be something like:
while ($row = mysql_fetch_array($query)) {
$userID = $row['user_id'];
$songID = $row['song_id'];
$points = $row['points'];
if($songID-$points==1){
echo $userID."<br>";
}
But this will print out every occasion of userID where the song-id - points=1.
I need to print out only these user_id's that have all the values =1 and the username must echo'd only once.
EDIT:
SELECT DISTINCT user_id WHERE (song_id - points) = 1
This is half way there. This echo's user_ids' where the song_id - points = 1, but if the user is reordered (i use jQuery sortable) the list, then there can be some rows that is "song_id - points = 1".
My script must echo only these user_id-s, where users every song_id - points = 1, not only one
SELECT DISTINCT user_id FROM table WHERE (song_id - points) = 1
After edit:
SELECT table.user_id
FROM table
LEFT JOIN (
SELECT user_id, COUNT(*) AS C FROM table) AS T2
ON table.user_id = T2.user_id
WHERE (table.song_id - table.points) = 1
GROUP BY table.user_id
HAVING COUNT(*) = T2.C
You can first filter the users which has modified point values:
SELECT DISTINCT user_id FROM table
WHERE (song_id - points) != 1
Then you can use fetch the users which doesn't fit the above condition:
SELECT DISTINCT user_id FROM table
WHERE user_id NOT IN (
SELECT DISTINCT user_id FROM table
WHERE (song_id - points) != 1
)
According to your last edit this last SQL statement might work.
You can check a working example.
Here is what you're looking for:
select user_id from (
select user_id, if(song_id - points = 1, 0, 1) flag from t
) as S
group by user_id
having sum(flag) = 0
And here is a working example.
In case I didn't understand the requirements this shows all users who don't even have one row in which song_id - points != 1, i.e, all users who have all rows that match song_id - points = 1
Or maybe, if you prefer a different approach that might be more efficient:
select distinct t1.user_id from t t1
where not exists (
select * from t t2
where t2.song_id - t2.points != 1 and t1.user_id = t2.user_id
)
Here is the working example.
Not sure I understand the why of the situation, but a simple control-break structure will achieve the desired result ...
$old_id = '';
$good = false;
while($row = mysql_fetch_array($query)){
//check to see if we have a new user ...
if($row['user_id'] != $old_id){
//check to see if all values were == 1
if($good){
echo $old_id . '<br />';
}
//re-initialize variables
$good = true;
$old_id = $row['user_id'];
}
//if value != 1, we won't print the user ...
if($row['song_id'] - $row['points'] != 1){
$good = false;
}
}
//final end-of-loop condition ...
if($good){
echo $old_id . '<br />';
}
OK, here's a query that's a lot more simple than the join above:
SELECT user_id, sum(song_id) as song_total, sum(points) as point_total, count(*) AS cnt FROM table GROUP BY user_id
If the difference between song_id and points is 1 for every song, then the difference between the totals will equal the number of rows for that user ... so using this query:
while($row = mysql_fetch_array($query)){
if($row['cnt'] == ($row['song_total'] - $row['point_total'])){
echo $row['user_id'] . '<br />';
}
}