mysql select and where over several tables (very tricky) - php

I have 4 Tables (listed bellow) and need:
get last 10 Chats from Room 3 without banned users
show nickname for fromuserid
HIDE Users $userid dont like to see table "HIDE"
Table 1 "chats"
ID(autoinc) fromuserid roomid text
1 23 3 bla
2 14 1 bla
3 11 3 bal
Table 2 "user" /shorted/
ID(autoinc) nickname banned
1 chris 0
2 paul 1 // 1 = banned
Table 3 "hide"
ID(autoinc) orguser hideuser
1 12 3
2 33 12
Right now i solved it with PHP Routine, but I have to go through EACH result and make always a new query, that needs too long;
$userid = 1; // actual user
// List all chats and show userid as nickname
$sql_com = "SELECT user.id, user.nickname, chats.text, chats.id ".
" FROM chats, user".
" WHERE ".
" chats.fromuserid = user.id ".
" AND chats.roomid = 3 ".
" AND user.banned != 1 ".
" ORDER BY chats.id DESC";
$result = mysql_query ($sql_com);
$count = 0;
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
$dontshow = false;
// Filter : dont show users $userid dont like to see (table "hide")
$sql_com2 = "SELECT id from hide WHERE ( (orguser = ".$userid.") AND (hideuser = ".$row[0].") ) ";
if ($result2 = mysql_query ($sql_com2))
{
if (mysql_num_rows($result2) > 0) $dontshow = true;
}
// Output
if ($dontshow == false)
{
$count++;
echo "Nickname: ".$row[1]." Text: ".$row[2];
}
if ($count > 10) break;
}
Btw. I made already some improvments, so the actual question may not fit with all answers (thanks for your help till now)
Finaly its now just about to integrate the filter "dont show people listed in table "hide" for my actual user".

I think you need something along these general lines. I've done it slightly different from your question. Instead of getting the top 10 then removing records. It gets the top 10 records which would not be hidden.
SELECT c.ID, c.fromuserid, c.roomid, c.text, u.nickname
FROM chats c
JOIN user u ON c.fromuserid = u.id
where c.roomid = 3 AND user.banned = 0
AND NOT EXISTS(
SELECT * FROM hide h
WHERE h.hideuser = c.fromuserid
AND orguser = $userid)
ORDER BY c.ID DESC
LIMIT 0,10

Not tested but it would be something like:
$sql_com = "SELECT us.id, us.nickname, ch.text, ch.id ".
" FROM chats ch, ".
" user us, ".
" hide hi, ".
" banned ba, ".
" WHERE ".
" us.id != hi.hideuser ".
" us.id != ba.user ".
" us.id = ch.fromuserid ".
" AND ch.roomid = 3 ".
" ORDER BY ch.id DESC LIMIT 0,10";

Although I can't immediately find a simple way to answer your question as-is, I can point you in the right direction:
http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
Using subqueries should enable you to go and select from both blocked and hidden tables, and using those in your original query.

Related

check if exist inside two column

need a help with a PHP/MySQL issue. I have a table named bids and two column named buyer and tagged both using int.
buyer
--------------
8
5
2
tagged
--------------
5
4
1
I'm trying to detect multiple same entry number. I want if a same number appears on both of the column it shouldnt display on the menu list anymore, hope yo understand.
Any tip?
code below
$query = "SELECT b.auction, b.buyer, b.bid, b.bidwhen, b.quantity, b.willwin, b.tagged, b.balance, u.nick, u.rate_sum FROM " . $DBPrefix . "bids b
LEFT JOIN " . $DBPrefix . "users u ON (u.id = b.bidder) WHERE b.auction = :auc_id
ORDER BY b.bid asc, b.quantity DESC, b.willwin asc"; $params = array(); $params[] = array(':auc_id', $id, 'int');

How to make ranking system in PHP

I have problem. .
In my case i make championship. . You know, the winner is determined by the highest value. .
Example :
$sql = "SELECT bla bla bla FROM `user` ORDER BY `point` DESC";
$result = mysql_query($sql);
$i=0;
while($row = mysql_fetch_array($result)) {
$1++;
echo "rank ".$i." is ".$row['name']." with point ".$row['point'].";
}
It's will show
rank 1 is abc with point 10
rank 2 is def with point 9
rank 3 is ghi with point 8
rank 4 is jkl with point 7
rank 5 is mno with point 7
rank 6 is pqr with point 3
rank 7 is stu with point 1
The question. .
look the result. . rank 4 and rank 5 have same point. . how to make
they in same possition ??
how to auto detect title of champions like rank 1 is the big boss, rank 2 is a boss, rank 7 is worker ??
how to tell ex: you in possition 6 ??
$sql = "SELECT bla bla bla FROM `user` ORDER BY `point` DESC";
$result = mysql_query($sql);
if( !$result ){
echo 'SQL Query Failed';
}else{
$rank = 0;
$last_score = false;
$rows = 0;
while( $row = mysql_fetch_array( $result ) ){
$rows++;
if( $last_score!= $row['point'] ){
$last_score = $row['point'];
$rank = $rows;
}
echo "rank ".$rank." is ".$row['name']." with point ".$row['point'].";
}
}
This code will also adjust the rankings properly - such as:
rank 1 is Adam Aarons with point 100
rank 2 is Barry Blue with point 90
rank 2 is Betty Boop with point 90
rank 4 is Charlie Chaplin with point 80
Note that there is no "rank 3", as "Charlie Chaplin" is actually the fourth-highest scorer.
If you do not want this behaviour, then simply replace $rank = $rows; with $rank++;
ad 1. group by point, add #curRow := \#curRow + 1 AS row_numbe to select the current row number which will be the rank position
ad 2. left join title_dict on row_number = title_dict.id
where title dictionary is table with title_id and title name dictionary
ad 3. select from your select on id = your id
Actually, a very easy way to order players with same amount of points is to add a column "points_last_update" containing the timestamp of the last update to the "points" column. Then you just add the "points_last_update" to the ORDER BY in your sql statement. That way, the player who has reached the points the first gets the higher ranking, wich is logic.
Save the last score and make sure it does not equal the current score before you increment.
$sql = "SELECT bla bla bla FROM `user` ORDER BY `point` DESC";
$result = mysql_query($sql);
$i=0;
$lastscore = NULL;
while($row = mysql_fetch_array($result)) {
if ($lastscore != $row['point']){
$i++;
}
echo "rank ".$i." is ".$row['name']." with point ".$row['point'];
$lastscore = $row['point'];
}

sql update multiple rows with case in php

I am trying to update 11 rows at a time - cricket team (11 players) posted from a form page before, and then I want to update the first table called with these players. (The table includes player, order and team.)
<?php
session_start();
// Edit this to connect to your database with your username and password
$db_name="a1467234_cricket"; // Database name
$tbl_name="statistics"; // Table name
// Connect to server and select databse.
$conn = mysql_connect("mysql17.000webhost.com","*******","*******") or die(mysql_error());
mysql_select_db("$db_name")or die("cannot select DB");
$one = $_POST["one"];
$two = $_POST["two"];
$three = $_POST["three"];
$four = $_POST["four"];
$five = $_POST["five"];
$six = $_POST["six"];
$seven = $_POST["seven"];
$eight = $_POST["eight"];
$nine = $_POST["nine"];
$ten = $_POST["ten"];
$eleven = $_POST["eleven"];
$team = $_POST["team"];
$sql = "UPDATE first
SET player = (CASE
WHEN order = 1 ='$team' THEN '$one'
WHEN order = 2 AND team ='$team' THEN '$two'
WHEN order = 3 AND team ='$team' THEN '$three'
WHEN order = 4 AND team ='$team' THEN '$four'
WHEN order = 5 AND team ='$team' THEN '$five'
WHEN order = 6 AND team ='$team' THEN '$six'
WHEN order = 7 AND team ='$team' THEN '$seven'
WHEN order = 8 AND team ='$team' THEN '$eight'
WHEN order = 9 AND team ='$team' THEN '$nine'
WHEN order = 10 AND team ='$team' THEN '$ten'
WHEN order = 11 AND team ='$team' THEN '$eleven'
ELSE player
END
WHERE order IN (1,2,3,4,5,6,7,8,9,10,11))";
echo "Updated team selection";
mysql_close($conn);
?>
Does anyone know how to get the update script working please? No errors are displayed, and it just doesn't change the database.
You need a mysql_query($sql); to execute your query on the database
Using for loop might be easier, neat and smarter way for your query. This might be little helpful for you:
<?php
for($i=1;$i<$count;$i++) {
$updatesql="update first set player ='".$_POST['player_'.$i]"' where team ='".$_POST['team_'.$i]"' ";
mysql_query($updatesql);
}
?>
You might need slight modification with this one.
for eg. you need to post data in this way:
player_1, player_2 etc. and team in team_1, team_2 etc.
bviously, you are missing a closing parenthesis ')' after the END.
By the way, the first case condition (order = 1 ='$team') doesn't seem to make any sense.
Anyway, the query below should work. Please note that the . . . would need to be populated in the same pattern as the first and second players.
$sql = "
UPDATE first a,
(
SELECT 1 AS `order`, '{$one}' AS player, '{$team}' AS team
UNION ALL
SELECT 2 AS `order`, '{$two}' AS player, '{$team}' AS team
.
.
.
UNION ALL
SELECT 11 AS `order`, '{$eleven}' AS player, '{$team}' AS team
) b
SET a.player = b.player
WHERE a.`order` = b.`order`
AND a.team = b.teamenter
";

simple php mysql search engine with checkboxes

I would like to do a search engine for my webpage.
I have several tables in my mysql database and i would like them
combined when user
Table users
id name age country vip profile_image
1 nick 23 sweden 1 yes
2 michael 20 germany 0 no
3 laura 19 usa 1 yes
4 gary 33 china 1 yes
Table online
id user_id online
1 1 1
2 2 1
3 4 1
user_id is connected to id in users table
Now i have checkboxes
[ ] Those which are online
[ ] Those which are vip
[ ] Those with profile image
Im coding my page in PHP and im trying to figure how to include certain
searches in a sql query if certain checkbox is checked.
I can have tons of options here. Example if no checkbox is checked,
iff on you want to search for those which are online, how do i go in to the second table?
I hope you get my point here. I really hope someone could help me
and give me an working example of the php & sql query.
Cheerz!
First you have to check which checkboxes have been checked. Then you must write MySQL-query with PHP based on that information. You must think in every checkbox, what information it needs to check. If your database is well written, there is seldom a problem that two options affect each other. If information is in users-table, you need just write line to where-clause. If you need to join table to users-table to get information you need to do that too. Here is an example
$query = "";
$query .= "SELECT users.* FROM users";
if ($include_online == 1) {
$query .= " LEFT JOIN online ON online.user_id = users.id";
}
$query .= " WHERE";
if ($include_vip == 1) {
$query .= " users.vip = 1 AND";
}
if ($include_image == 1) {
$query .= " users.profile_image = 'yes' AND";
}
if ($include_online == 1) {
$query .= " online.online = 1 AND";
}
$query .= " users.name LIKE '%".$search_string."%'";
You need to form a query something like the following:
SELECT users.name, users.age, users.country
FROM users
LEFT JOIN online ON user.id = online.user_id
WHERE ((user.vip = 1) && (online.online = 1))

Mysql array and data

Mysql query and PHP code that I'm using to get users from the database that meet certain criteria is:
$sql = mysql_query("SELECT a2.id, a2.name FROM members a2 JOIN room f ON f.myid = a2.id
WHERE f.user = 1 AND a2.status ='7' UNION SELECT a2.id, a2.name FROM members a2
JOIN room f ON f.user = a2.id WHERE f.myid = 1 AND a2.status ='7' GROUP BY id")
or die(mysql_error());
while ($r = mysql_fetch_array($sql))
{
$temp[] = '"'.$r[0].'"';
}
$thelist = implode(",",$temp);
The query that follows get the list of members with new galleries by using array from the previous query.
$ft = mysql_query("SELECT id, pic1 FROM foto WHERE id IN ($thelist) AND
pic1!='' ORDER BY date DESC LIMIT 10");
while ($f = mysql_fetch_array($ft))
{
echo $f['id']." - ".$f['pic1']."<br/>";
}
These queries working fine but I need to get the name for every user listed in second query. This data is in the first query in the column name. How can I get it listed beside '$f['id']." - ".$f['pic1']'?
While I might just alter the first query to pull the galleries at the same time, or change the second query to join and get the name, you could keep the same structure and change a few things:
In the loop after the first query when building $temp[], also build a lookup table of user id to user name:
$usernames[$r[0]] = $r[1];
Then in your output loop, use the id (assuming they are the same!) from the second query to call up the user name value you stored:
echo $f['id'] . " - " . $f['pic1'] . " - " . $usernames[$f['id']] . "<br/>";

Categories