I'm trying to do nested mysql query but I'm failing
it's as simple as I have a table called 'todo' which is for saving to-do list
when I do
well this code is just to show how I wanna do it logically , I know it doesn't work
and I think it probably needs JOIN or UNION but I couldn't do it
$result = mysqli_query($con,"SELECT type FROM todo WHERE user = '$username' GROUP BY type");
while($row = mysqli_fetch_array($result))
{
echo '<td>- '." ".$row['type'].'</td>';
echo "</br>";
$result2 = mysqli_query($con,"SELECT titleFROM todo WHERE type= '$row['type']'");
while($row = mysqli_fetch_array($result2))
{
echo '<td>-- '." ".$row['title'].'
}
</td>';
echo "</br>";
}
I want the result to like
-Work
--Mr Jack
--Company
-School
--Android Class
--Entrepreneurship
--php development
and so on...
Your inner loop overwrites the outerloop's $row variable. Try using a different variable name in the inner loop. Also, there's an error in your inner loop's SQL query (missing space between the tablename and FROM keyword).
Related
I am trying to read table data and display in on a table the only thing is that i am trying to read it on 2 tables. The 2 tables have the same structure and i have tried it with the code below but nothing happens.
$sql = "SELECT pricedatamt5.symbol_name, pricedatamt5.symbol_bid, pricedatamt5.symbol_ask, pricedatamt4.symbol_bid, pricedatamt4.symbol_ask FROM pricedatamt5 LEFT JOIN pricedatamt4 ON pricedatamt5.symbol_name = pricedatamt4.symbol_name WHERE symbol_name='".$value."'";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row["symbol_date"]."</td>";
echo "<td>".$row["symbol_bid"]."</td>";
echo "<td>".$row["symbol_ask"]."</td>";
echo "</tr>";
}
I hope you can help me with this one because i am really having a hard time especially on retrieving data from 2 tables.
Thanks...
if you need the union your sql query will be:
$sql = "SELECT pricedatamt5.symbol_name, pricedatamt5.symbol_bid, pricedatamt5.symbol_ask FROM pricedatamt5 WHERE symbol_name='".$value."'"."
UNION
SELECT pricedatamt4.symbol_name, pricedatamt4.symbol_bid, pricedatamt4.symbol_ask FROM pricedatamt4 WHERE symbol_name='".$value."'";
otherwise you should clarify your question.
Well I'm trying to get all the times that a String are repeated in two tables using a comun column and getting all the results with a While, like that:
$result = mysql_query("SELECT * FROM hits") or die(mysql_error());
while($row = mysql_fetch_assoc( $result ))
{
$result=mysql_query("SELECT COUNT(app) FROM info WHERE app='$row[page]'");
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
$toip = $row[0] ;
}
echo '<td bgcolor="#75D169">';
echo "$toip";
echo '</td>';
}
But it doesn't show it very well as you can see it here: http://ikillcraft.a0001.net/counter/view.php?pass=test
The output would be:
Instalaciones de 4 0
Instalaciones de IkillLauncher 3 3
Instalaciones de gogogoa 3 0
Instalaciones de MasterShell 0 0
But I don't know how to do it. :(
Using a single piece of SQL, something like this would do it:-
$result = mysql_query("SELECT a.page, COUNT(b.app) AS AppCount
FROM hits a
LEFT OUTER JOIN info b
ON a.page = b.app
GROUP BY a.page";
while($row = mysql_fetch_assoc( $result ))
{
echo '<td bgcolor="#75D169">';
echo $row['AppCount'];
echo '</td>';
}
Note I do not know your column names, and you should have all the non aggregate column names in the GROUP BY clause (ie, anything except the ones in the COUNT in this case)
I don't know your table structure, so I am doing guesswork here, but this should work:
SELECT hits.page, appgrouped.apphit
FROM (hits)
LEFT JOIN (SELECT COUNT(app) as apphit, app
FROM info
GROUP BY app) AS appgrouped ON appgrouped.app = hits.page
This would be quite slow - depending on how big:
SELECT COUNT(app) as apphit, app
FROM info
GROUP BY app
This is, if it is big, then the above join will be very slow, and in that case, PHP code would be a better solution (yes it would be faster).
OK,
In this query I am displaying the sales for a particular person, matching the passport number from the current form I am working on.
What I want to do however, is to sum the total sales and display it, excluding records which have been marked as paid.
I am having trouble because "paid" does not existent in the current form I am working on as a variable, nor the table it relates to.
I canĀ“t use row['paid'] as I need to do this query outside of the while loop.
What should I do in this situation?
$sqlstr = mysql_query(
"SELECT * FROM sales where passport = ".
"'{$therecord['passport']}'");
if (mysql_numrows($sqlstr) != 0) {
echo "<b>Sales for {$therecord['firstname']} ".
"{$therecord['lastname']}</b><br />";
echo "<table><tr>";
echo '<tr><th align="left">Name</th><th align="left">Quantity</th>".
"<th align="left">Cost</th></tr>';
while ($row = mysql_fetch_array($sqlstr)) {
echo "<td>{$row['product']}</td>";
echo "<td>{$row['quantity']}</td>";
echo "<td>{$row['cost']}</td>";
echo "</tr>";
}
}
echo "</table>";
$sqltotal = mysql_query(
"SELECT SUM(cost) as total FROM sales where passport = ".
"'{$therecord['passport']} AND {$therecord['paid']} <> 1'");
$row = mysql_fetch_array($sqltotal);
echo "<br /><b>Total Owing: {$row['total']}</b>";
You could either create a MySQL view, of look at SQL joins. I'm not sure on your database structure, but you should have a SQL query like this:
SELECT SUM(sales.cost) AS total
FROM sales, table2
WHERE sales.passport = '$passport_id'
AND sales.passport = table2.passport
AND table2.paid = '1'
Not sure as that was wrote off-hand. Again, it'd be better if we knew the structure of your tables.
you've misplaced simple quote in :
"'{$therecord['passport']} AND {$therecord['paid']} <> 1'"
it must be :
"'{$therecord['passport']}' AND {$therecord['paid']} <> 1"
I have put together the following code, the problem is that each while loop is only returning one set of data.
$result = mysql_query("SELECT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' GROUP BY date");
$i = 1;
echo "<table cellspacing=\"10\" style='border: 1px dotted' width=\"300\" bgcolor=\"#eeeeee\">";
while ($row = mysql_fetch_assoc($result))
{
$date=date("F j Y", $row['date']);
echo $date;
echo "
<tr>
<td>Fixture $i - Deadline on $date</td>
</tr>
";
$result = mysql_query("SELECT * FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' AND date = '$row[date]' ORDER BY date");
while ($row = mysql_fetch_assoc($result))
{
extract ($row);
echo "
<tr>
<td>$home_user - $home_team V $away_user - $away_team</td>
</tr>
";
}
$i++;
}
echo "</table>";
I should get many dates, and then each set of fixture below.
At the moment, the first row from the first while loop is present, along with the data from the second while loop.
However, it doesn't continue?
Any ideas where I can correct this?
Thanks
Replace
$result = mysql_query("SELECT * FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' AND date = '$row[date]' ORDER BY date");
while ($row = mysql_fetch_assoc($result))
with
$result1 = mysql_query("SELECT * FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' AND date = '$row[date]' ORDER BY date");
while ($row = mysql_fetch_assoc($result1))`
What happens with your current code is that after executing internal while, next call (in external loop)to mysql_fetch_assoc($result) always returns false (because you just iterated through it in internal loop). All you need is to use a different variable in internal loop.
You're overwriting the $result variable. Change the second one to $result2 or something and see what happens. Make sure you do it when you set the variable, and use it in the query.
You are changing your $result variable in your loop so it is at the end after the inner while loop has run.
you just mixing variables. second result and row should be named differently.
though it would be better to make it with one single query
Well you've got the answer to your question.
I just want to add that usually you can write a smarter SQL query and manage without an inner query with it's loop. And your code will work a lot faster if you'll have 1 query instead of N+1.
LEFT JOIN usually can be used to replace inner looping. Example:
SELECT DISTINCT A.date, B.* FROM table_fixtures A
LEFT JOIN table_fixtures B ON A.date = B.date
WHERE B.compname = "a value"
However this time it looks illogical. I think what you actually do is achievable with a simple query like this:
SELECT * FROM table ORDER WHERE compname="something" ORDER BY date
You are reusing the same variables over for your inner loop and its breaking the outer loop.
Change your inner loop to something like:
$result2 = mysql_query("SELECT * FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' AND date = '$row[date]' ORDER BY date");
while ($row2 = mysql_fetch_assoc($result2))
{
extract ($row2);
echo "
<tr>
<td>$home_user - $home_team V $away_user - $away_team</td>
</tr>
";
}
On a different note - why do you have a GROUP BY date in the first row, when all you have in the projection list is the date?
I'm coding in PHP/MySQL and have the following query to fetch products and product group data:
SELECT products.id,products.name,product_groups.id,product_groups.name
FROM products
INNER JOIN product_groups
ON products.id=product_groups.id
WHERE products.name LIKE '%foobar%'
ORDER by product_groups.id ASC
So this query fetches products and orders them by product group. What I would like to have is to display product_groups.name just once for each product grouping. So even if I have ten shoe products, the group name "Shoes" is only displayed once.
I'm using the following PHP to print out the results:
while ($data = mysql_fetch_array($result))
If you want it done in the MySQL query, it is honestly more trouble than it's worth. For one, the syntax is really wonky (as I recall) to have a group name listed at the top of each grouping. And the results are still treated as rows, so the group name will be treated like a row with all the other columns as Null, so you won't really save any time or effort in the PHP script as it has to do an if statement to catch when it hits a group name instead of the group data.
If you want it done by the PHP while loop, Johan is on the right track. I use the following for a similar situation:
$result = $sql->query($query);
$prev_group = "";
while($data = $result->fetch_assoc()){
$curr_group = $data['group'];
if ($curr_group !== $prev_group) {
echo "<h1>$curr_group</h1>";
$prev_group = $curr_group;
}
else {
echo $data;
.....
}
Obviously the echo data would be set up to echo the parts of the data the way you want. But the $prev_group/$curr_group is set up so that the only time they won't match is when you are on a new group and thus want to print a header of some sort.
while($data = mysql_fetch_assoc($result)){
if($data['product_groups.name'] != $groupname){
echo "Groupname: ".$data['product_groups.name']."<br />";
$groupname = $data['product_groups.name'];
}
echo "ID: ".$data['products.id']."<br />";
echo "Name: ".$data['products.name']."<br />";
}
Maybe you can do like this!?