how to solve this mysql query - php

I have 3 mysql tables
user(u_id(p),name),
team(t_id(p),u_id(f),t_name,t_money,days_money) and
history(t_id(f),day,d_money).
Now I have to display leaderboard using php.
I tried this.
SELECT t_id FROM team;
got result.
then,
in for loop
foreach($tid_all as $tid)
{
$que = $db_con->prepare("SELECT d_money, t_name FROM team, history WHERE t_id= '".$tid['t_id']."' && day='1'");
$que->execute();
while($info = $que->fetch(PDO::FETCH_NUM))
{
echo "<tr>";
echo "<td>".$info[0]."</td>";
echo "<td>".$info[1]."</td>";
echo "</tr>";
}
}
but it didnt work. any solution?
Solution 1:
i tried this and it worked.
`SELECT d_money, t_name FROM team, history WHERE history.t_id=$tid['t_id'] AND team.t_id=history.t_id`
is it correct way or not?
thanks everyone for help.
Question : is it possible to order the result table by d_money? i want it in descending order.

Replace && with AND.Try like this :
"SELECT d_money, t_name FROM team, history WHERE t_id= '".$tid['t_id']."' AND day='1' order by d_money DESC "

There is no && in MySQL Query. Replace that with AND Operator on your query.

Since you want to get the data from the two tables, then JOIN the two tables instead of doing that with a loop:
SELECT
h.d_money,
t.t_name
FROM team AS t
INNER JOIN history AS h ON t.t_id = h.t_id;
Run this single query once and you will get what you want. You can also add a WHERE clause at the end of it the way you did in your query.

try this
SELECT d_money, t_name FROM team, history WHERE team.t_id= '".$tid['t_id']."' AND history.t_id= '".$tid['t_id']."' && day='1'

Can you replace
WHERE t_id= '".$tid."' AND day='1'
instead of
WHERE t_id= '".$tid['t_id']."' && day='1'

Related

PHP, MYSQL: Select inside a while Loop?

I am requesting your advice about the following:
I have two tables:
Customers and Orders.
I am printing the data of customers inside a table using a while loop:
$sql = "SELECT * FROM wccrm_customers where status = '1' order by date desc";
$result = mysql_query($sql, $db);
while ($daten = mysql_fetch_array($result)) { ?>
echo $daten[id];
echo $daten[name] . ' ' . $daten[vorname];
echo $daten[email];
echo $daten[telefon];
} ?>
Now I try to add a new field in this list: Purchased YES/NO. As we have more customers then buyers, we want to show whether someone has bought or not:
The Connection between this two tables is the first/lastname in both tables!
So if customer.name = orders.name and customer.firstname = orders.firstname I want to echo "YES" if not then "NO"
I tried with a JOIN, but here I just get the results who are in both table:
SELECT *
FROM wccrm_customers AS k
INNER JOIN wccrm_orders AS o
ON o.namee = k.name AND o.firstname = k.firstname
but I need to have all of the customers and the ones who are in both lists marked...
Is this possible? If yes: How can I achieve this?
Thank's for your advice!
Kind regards,
Stefan
This has nothing to do with PHP, or with while loops; you just need to form your join properly:
SELECT DISTINCT
`k`.*,
`o`.`namee` IS NOT NULL AS `Purchased`
FROM `wccrm_customers` AS `k`
LEFT JOIN `wccrm_orders` AS `o`
ON
`o`.`namee` = `k`.`name`
AND `o`.`firstname` = `k`.`firstname`
Read more about the different join types: http://www.sql-join.com/sql-join-types/
(images courtesy of that site, which also contains an example and discussion of almost exactly what you're trying to do!)
By the way, you must have missed the massive red warning banner in the manual about using the deprecated (now removed) mysql_* functions. You should stop doing that! Use MySQLi or PDO instead.
a shorter one
SELECT DISTINCT k.*, IF(o.namee IS NULL, 'no', 'yes') purchased
FROM
wccrm_customers AS k
LEFT JOIN wccrm_orders AS o USING (namee,firstname)

How can I convert these two queries in a loop into a single JOINed query?

I am currently trying to get data from my table (mostKills by Weapon in a table with over 300 kills). Initially I did a normal query
$q = $mysql->query("SELECT * FROM `kills`") or die($mysql->error);
but when I tried to
$query2 = $mysql->query("SELECT `killerID`, COUNT(`killerID`) AS tot_kills FROM `kills` WHERE `killText` LIKE '%$gun%' GROUP BY `killerID` ORDER BY `tot_kills` DESC;") or die($mysql->error);
$kData = $query2->fetch_assoc();
$query3 = $mysql->query("SELECT `Username` FROM `players` WHERE `ID` = '" . $kData['killerID'] . "'") or die($mysql->error);
$uData = $query3->fetch_assoc();
$array[$gun]['Kills']++;
$array[$gun]['Gun'] = $gun;
$array[$gun]['BestKiller'] = $uData['Username'];
$array[$gun]['killAmount'] = $kData['tot_kills'];
function sortByKills($a, $b) {
return $b['Kills'] - $a['Kills'];
}
usort($array, 'sortByKills');
foreach($array as $i => $value)
{
// table here
}
I had to do it in a while loop, which caused there to be around 600 queries, and that is obviously not acceptable. Do you have any tips on how I can optimize this, or even turn this into a single query?
I heared JOIN is good for this, but I don't know much about it, and was wondering if you guys could help me
Try this...
I added a inner join and added a username to your select clause. The MIN() is just a way to include the username column in the select and will not have an impact on you result as long as you have just 1 username for every Killerid
SELECT `killerID`
, COUNT(`killerID`) AS tot_kills
, MIN(`Username`) AS username
FROM `kills`
INNER JOIN `players`
ON `players`.`id` = `kills`.`killerid`
WHERE `killText` LIKE '%$gun%'
GROUP BY `killerID`
ORDER BY `tot_kills` DESC
SELECT kills.killerID, count(kills.killerID) as killTotal, players.Username
FROM kills, players
WHERE kills.killText
LIKE '%$gun%'
AND players.ID` = kills.killerID
GROUP BY kills.killerID
ORDER BY kills.tot_kills DESC
Here is a good place to learn some more about joins.
http://www.sitepoint.com/understanding-sql-joins-mysql-database/
The best way is to have your own knowledge so you can be able to tune up your select queries.
Also put more indexes to your DB, and try to search and join by index.

why i can't display my records in php mysql?

I have records in my database but I can't display them. Can someone check my codes, please. I'm just an amateur web developer. Thanks for any help.
<?php
$groups=mysql_query("SELECT * FROM groups ORDER BY id ASC");
$g_res=mysql_affected_rows();
if($g_res>0)
{
while($row=mysql_fetch_array($groups))
{
$g_id=$row['id'];
$g_name=$row['g_name'];
$members=mysql_query("SELECT * FROM members WHERE group='$g_id'");
$m_res=mysql_affected_rows();
if($m_res>0)
{
while($row2=mysql_fetch_array($members))
{
$m_id=$row2['id'];
$m_name=$row2['m_name'];
$m_email=$row2['m_email'];
echo "<tr><td>$m_name<br/>($g_name)</td><td>$m_email</td></tr>";
}
}
else
{
echo "<tr><td colspan=2>Nothing to display</td></tr>";
}
}
}
else
{
echo "<tr><td colspan=2>Error</td></tr>";
}
?>
With this code I get the else result which is Error. If I remove WHERE group='$g_id' from the query, all of my records are displayed randomly, but I'd like to show my records (members) by group.
You need to escape reserved words in MySQL like group with backticks
SELECT * FROM members WHERE `group` = '$g_id'
^-----^-------------here
You can also spare the inner loop when you join your data like this
select g.id as gid, g.g_name, m.id as mid, m.m_name, m.m_email
from groups g
inner join members m on g.id = m.group
order by g.id asc
This is easier and will increase performance since you don't need to execute a lot of queries but just one.
Also please don't use mysql_* functions in new code.
They are no longer maintained and are officially deprecated.
Learn about Prepared Statements instead, and use PDO or MySQLi. See this article for a quick overview how to do it and why it is so important.
Try like
$members=mysql_query("SELECT * FROM members WHERE `group` = '".$g_id."');
or simply
$members=mysql_query("SELECT * FROM members WHERE `group` = '$g_id'");
You have to concatenate your variables.
Try this:
$members=mysql_query("SELECT * FROM members WHERE `group`='".$g_id."'");
And
echo "<tr><td>".$m_name."<br/>(".$g_name.")</td><td>".$m_email."</td></tr>";

SQL SELECT query echoing twice even with DISTINCT

I am creating a simple SQL query in PHP - and for some reason, even when DISTINCT is used, it shows twice like this:
BC
BC
OH
OH
TX
TX
Here is my code:
<?php
$sql = "SELECT DISTINCT `title`,`extra_fields_search` FROM `blahblah_items` WHERE catid=336 ORDER BY `blahblah_items`.`extra_fields_search` ASC ";
$partnerlisting= mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($partnerlisting))
foreach($row as $cname => $cvalue){
echo '<li>'.substr($row[extra_fields_search], 0, 2).'</li><br>';
}
;
?>
How can I make it so it prints out only one of each?
SELECT
`title`,
`extra_fields_search`
FROM
`blahblah_items`
WHERE
catid=336
GROUP BY
SUBSTRING(extra_fields_search,1,2) # here. group by first two characters of extra_fields_search
# or just "GROUP BY extra_fields_search", depends what you need
ORDER BY
`blahblah_items`.`extra_fields_search` ASC
SELECT DISTINCT a,b FROM table works in same way as SELECT a,b FROM table GROUP BY a,b
Please follow documentation:
http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
Distinct make sure that you get unique rows. It does not make sure you will get unique column values. In your case if you consider all the fields in the result, you will notice that each row is different from the other by at least one field.
SO you will never get
Col1 Col2
A B
A B
But you can get
Col1 Col2
A B
A C
Try:
SELECT `title`, group_concat(distinct `extra_fields_search`)
FROM `blahblah_items`
WHERE catid=336
Group BY `title`
ORDER BY 2
try this
SELECT `title`,`extra_fields_search`
FROM `blahblah_items` WHERE catid=336
Group BY extra_fields_search
ORDER BY `blahblah_items`.`extra_fields_search` ASC
edit :
try this in your code
while($row = mysql_fetch_assoc($partnerlisting))
$rows[] = $row;
foreach($rows as $row){
echo '<li>'.substr($row[extra_fields_search], 0, 2).'</li><br>';
}
;

mySQL query with JOIN on latest record not all records

The following code is used in a query for fetching records. It uses the electors.ID to find the corresponding voting_intention.elector from a second table.
$criteria = "FROM voting_intention,electors WHERE voting_intention.elector = electors.ID AND voting_intention.pledge IN ('C','P') AND electors.postal_vote = 1 AND electors.telephone > 0"
The problem is that some electors will have more than one pledge in the voting_intentions table.
I need it to match only on the latest voting_intention.pledge based on the field votin_intention.date for each elector.
What is the simplest way of implementing that.
The rest of the code:
function get_elector_phone($criteria){
$the_elector = mysql_query("SELECT * $criteria ORDER BY electors.ID ASC"); while($row = mysql_fetch_array($the_elector)) {
echo $row['ID'].','; }
}
You could use a sub-select with the MAX() function. Add the following into your WHERE clause.
AND voting_intention.date = (select MAX(date)
from voting_intention vote2
where voting_intention.elector = vote2.elector)
Here is a SQLFiddle of the results.
So pretty much, you only want to bother looking at the most recent row that fits the first two criteria in your code. In that case, you would want to filter out the voting_intention table beforehand to only have to worry about the most recent entries of each. There's a question/answer that shows how do do that here.
Try selecting the following instead of voting_intention (from the answer of the linked question, some table and field names replaced):
SELECT voting_intention.*
FROM voting_intention
INNER JOIN
(
SELECT elector, MAX(date) AS MaxDate
FROM voting_intention
GROUP BY elector
) groupedintention ON voting_intention.elector = groupedintention.elector
AND voting_intention.date = groupedintention .MaxDate
Question url: How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

Categories