Output distinct values in SQL column with PHP - php

I have a table with two collumns (shortened), NAME and CATEGORY.
I want to output the number of distinct categorys. For an examle: Sport : 5 , Houses : 10.
I use this one:
$test = mysqli_query($con,"SELECT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
This work then I run the code in SQL Shell, but I have no clue on how to output it in PHP. I have searced Google up and down without any successfull solution.
Any help?
I want to output it in a table format.
EDIT: Here is my full code: (tablename is changed, and $con is removed)
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
while($row = mysql_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}

$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
echo "<table border='1'>";
while($row = mysqli_fetch_array($test)) {
echo "<tr>";
echo "<td>" . $row['lkategori'] . "</td>";
echo "<td>" . $row['count'] . "</td>";
echo "</tr>";
}
echo "</table>";
This will output all the categories and the count returned by the sql statement into a table. Also as a sidenote you should look into PDO.
EDIT: to make sure you do get the distinct values you should use the DISTINCT keyword in your sql statement:
$test = mysqli_query($con,"SELECT DISTINCT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");

use this
while($row = mysqli_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
Thanks

Related

Cannot sort by including the date

When I enter the vehicleID and Date, the records must be sorted by using both vehicle ID and Date, however it doesn't get sorted from the Date but only with the vehicleID. How can I achieve this ?
if ($vid != null && $datepicker != null) {
$conn = new Db();
$sql = "SELECT * FROM trip_details where vehicle_id = '".$vid."' AND date_t = '".$datepicker."'";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td> ". $row["trip_id"]."</td>";
echo "<td> ". $row["vehicle_id"]."</td>";
echo "<td> ". $row["total_trip_km"]."</td>";
echo "<td> ". $row["predict_fual"]."</td>";
echo "<td> ". $row["date_t"]."</td>";
// echo "<td><input type=\"submit\" value=\"view map\"></td>";
echo "</tr>";
}
}
SQL makes no guarantee on the order results are returned from a select query unless you explicitly add an order by clause, so the fact that you observe the returned records sorted by the vehicle_id is coincidental. You need to add an order by clause to the query:
ORDER BY vehicle_id, date_t
to sort you data by the columns you have define the name of columns in order by clause with order Acs(ascending) or Desc (descending)
e.g.
order by desc column1, asc column2
Order by needs to define to get the desired result.
try this
$sql="SELECT * FROM trip_details where
vehicle_id='".$vid."' AND date_t='".$datepicker."'
ORDER BY vehicle_id DESC,date_t DESC";

Printing table values in ascending order

I am trying to print out a users name and totalspent value in ascending order of totalspent. I.e, user that has spent the most will be outputed first then the next highest spender etc.
This is my current code, however, this only seems to output a single table row an infinite amount of times.
$query = "SELECT * FROM (
SELECT * FROM `members` ORDER BY `totalspent` DESC LIMIT 10) tmp order by tmp.totalspent asc";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
select member_name, totalspent from tmp order by totalspent desc;
still can you show snippet of your table and snippet of answer you desire
The best way I can prefer for you to join two tables. The code should like follows-
$query = "SELECT * FROM temp.tmp, mem.members WHERE temp.totalspend = mem.totalspend ORDER by temp.totalspend ASC";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
I believe, it will work for your smoothly... TQ

Show multiple table rows in a table

I have 2 tables called 0_vrs_american and 0_vrs_europe, and I need to display the rows of these tables in a single html table. So I wrote this code:
<?php
$con=mysqli_connect("localhost","aaa","bbb","my_mk7vrlist");
$result = mysqli_query($con,"SELECT 0_vrs_american.*, 0_vrs_europe.* FROM 0_vrs_american, 0_vrs_europe ORDER BY `vrs` DESC LIMIT 0 , 200");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $x . "</td>";
echo "<td>" . $row['playername'] . "</td>";
echo "<td>" . $row['contactable'] . "</td>";
echo "<td>" . $row['vrs'] . "</td>";
echo "</tr>";
$x = $x+1;
}
mysqli_close($con);
?>
I am pretty new with MySQL and so I googled about this topic and I found a syntax like the one you can see above. By the way I have no results in my page because the table is empty.
So: I must display in a HTML table the content of both sql tables, and the rows must be sorted according with the vrs (number that goes from 50000 to 99000). How could I solve my problem?
An alternative to the above is to select all the rows from those two tables as an inner select, and then order by vrs in the returned result set.
SELECT *
FROM
(
SELECT * FROM 0_vrs_american
UNION
SELECT * FROM 0_vrs_europe
) AS a
ORDER BY vrs
at first U need to define $x before the loop
then use the query like this
$result = mysqli_query($con,"SELECT 0_vrs_american.*, 0_vrs_europe.* FROM 0_vrs_american, 0_vrs_europe ORDER BY `vrs` DESC LIMIT 0 , 200") or die (__LINE__." ".mysqli_error($con));
so you will see the error and the line of the query
i just add or die (__LINE__." ".mysqli_error($con))
Separate the 2 queries and their results
merge both results into an array
sort the array as needed
output the array (generate table rows)

PHP dropdown to query for another dropdown to query for results

Right! I'm a complete PHP noob but have managed to completely blag/copy/paste/graft together some PHP that queries what I want it to query and return me a dropdown.
Now. I can bastardise this for another dropdown. HOWEVER. This dropdown should be returning results based on an array returned from the first query.
AND. Finally once this dropdown has been selected it should be printing the results in a table below.
I understand that I should be using Javascript to temporarily store the values returned by the dropdowns.
So it goes as such, I have three queries that all work in MySQL:
select id, name, replace(replace(arrange, 'c,', ''), '|', ',')
from cats
limit 10;
This query now returns the "arrange" in an array-friendly format which contains the subcategories which I simply copy and paste, but for this want to return as a string and query.
select id, name, Group_concat(replace(replace(arrange, 'i,', ''), '|', ',')) As Products_in_Category from cats
where id in (ARRAY FROM PREVIOUS QUERY REPLACE);
This now returns a massive array, that you guessed it, I want to define as a string and query to return for the final query.
select p.id,substring(c.name, 1, 60) As Name, c.code, sum(qty) As Sold
from cart c
join prods p on c.item = p.id
and order_status = ('Processed Order')
and p.id in ([ARRAY RETURNED FROM PREVIOUS GROUP_CONCAT)
group by code
order by sold desc
So, the code I have for the PHP is:
<?php
$host = '';
$user = '';
$pass = '';
$db = '';
//Database Connection
mysql_connect($host, $user, $pass)
or die('Could not connect: ' . mysql_error());
mysql_select_db($db)
or die ('Could not select database ' . mysql_error());
// SQL QUERY TO NAME
$sql = "select id, name, replace(replace(arrange, 'c,', ''), '|', ',')
from kcommerce_cats
where arrange like ('c,%')";
$result = mysql_query($sql);
echo "<select name='type'>";
while($row = mysql_fetch_assoc($result)){
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo "</select>";
?>
So how do I now select the replace as a string.
How do I then query that replace as the In for the 2nd dropdown.
And from there, how the devil should I declare the group_concat as a string to be queried for the final in.
Add to that I would love to be able to put all that in an HTML table.
I am asking a lot here but have the principles of what I want in my head, just not the PHP ability!!!
So I haven't managed to work out the dropdown/select side of things, but I have managed to answer the question of how to pass a result from one query and then query against that - also I have managed to print the results in an HTML table.
So, in order for the querying of the categories which will eventually be the basis of the whole page and its' dropdowns:
$query = "select id, name, replace(replace(arrange, 'c,', ''), '|', ',') As Arrange
from cats
where arrange like ('c,%') limit 10";
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
The above is doing the first query in preparation for the storing of the result as a string.
while ($row = mysql_fetch_array($result)) {
$arrange = $row['Arrange'];
}
echo $arrange;
mysql_free_result($result);
Now this is saying lookup the value of arrange from the first query, the echo prints it out so you can confirm the values returned. The important part is the $arrange that is now in the code to store that array.
//Query Subcategories
$query = "select id, name, Group_concat(replace(replace(arrange, 'i,', ''), '|', ',')) As Products from cats
where id in (".$arrange.")";
This is the subcategory query with the important addition of querying against the results from $arrange.
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysql_fetch_array($result)) {
$prodsarray = $row['Products'];
}
echo "<br>";
echo $prodsarray;
I have then repeated the process as above, returning the Group Concat as a string which can then be used as per the first line of the 2nd query above.
$query = "select p.id As ID,substring(c.name, 1, 100) As Name, c.code As Code, sum(qty) As Sold,
p.price As Price, format(p.price*1.2,2) As VAT, p.rrp As RRP, p.cost As Cost
from cart c
join prods p on c.item = p.id
and order_status = ('Processed Order')
and p.id in (".$prodsarray.")
and date_ordered < now()-interval 3 month
group by code
order by sold desc";
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
The next step is to echo the results from this query into a table.
echo "<table class='equalDivide' cellpadding='0'cellspacing='0' width='100%' border = '3'><tr>";
echo "<td width = '5%' align='center'>ID</td>";
echo "<td width = '35%'align='center'>Name</td>";
echo "<td width = '15%' align='center'>Code</td>";
echo "<td width = '7.5%' align='center'>Sold</td>";
echo "<td width = '7.5%' align='center'>Price</td>";
echo "<td width = '7.5%' align='center'>VAT</td>";
echo "<td width = '7.5%' align='center'>RRP</td>";
echo "<td width = '7.5%' align='center'>Cost</td>";
echo "</tr></table><br>";
Above is the hardcoding of the field names.
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_array($result)) {
echo "<table class='equalDivide' cellpadding='0'cellspacing='0' width='100%' border = '1'><tr>";
echo "<td width = '5%'>".$row['ID']."</td>";
echo "<td width = '35%'>".$row['Name']."</td>";
echo "<td width = '15%'>".$row['Code']."</td>";
echo "<td width = '7.5%'>".$row['Sold']."</td>";
echo "<td width = '7.5%'>".$row['Price']."</td>";
echo "<td width = '7.5%'>".$row['VAT']."</td>";
echo "<td width = '7.5%'>".$row['RRP']."</td>";
echo "<td width = '7.5%'>".$row['Cost']."</td>";
echo "</tr></table>";
}
This is the loop that fills the table with the results, notice the ['Sold'] under row is whatI declared the row as in the select query.
Next step is to turn the first two queries into dropdown selects, then I am done! Boom!

PHP: table structure

I'm developing a website that has some audio courses, each course can have multiple lessons. I want to display each course in its own table with its different lessons.
This is my SQL statement:
Table: courses
id, title
Table: lessons
id, cid (course id), title, date, file
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
Can someone help me with the PHP code?
This is the I code I have written:
mysql_select_db($database_config, $config);
mysql_query("set names utf8");
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<p><span class='heading1'>" . $row['course'] . "</span> </p> ";
echo "<p class='datum'>Posted onder <a href='*'>*</a>, latest update on " . strftime("%A %d %B %Y %H:%M", strtotime($row['date']));
}
echo "</p>";
echo "<class id='text'>";
echo "<p>...</p>";
echo "<table border: none cellpadding='1' cellspacing='1'>";
echo "<tr>";
echo "<th>Nr.</th>";
echo "<th width='450'>Lesso</th>";
echo "<th>Date</th>";
echo "<th>Download</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['nr'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . strftime("%d/%m/%Y", strtotime($row['date'])) . "</td>";
echo "<td><a href='audio/" . rawurlencode($row['file']) . "'>MP3</a></td>";
echo "</tr>";
echo "</table>";
echo "<br>";
}
?>
One thing that comes to mind is you're starting with lessons and pulling the course details over with it. That means you're going to have a new row per lesson with a joined course. You may want to sort by course (so they're grouped) then (in PHP) keep a tally of "current course". When the course changes, switch to new heading paragraph, table, etc.
Pseudo code:
$currentCourse = null; // intitialize the course
$query = your select sorted by course;
while ($row in $query)
{
if ($currentCourse != $row['course'])
{
if (!is_null($currentCourse))
{
// there was a course before it, close the current one
}
// begin setting up heading1, table beginning, etc.
$currentCourse = $row['course']; // set this as the active course
}
// dump the current row as a table entry
}
// close the table (same code as in the second if statement)
You close the while loop on line 8 of your code block. Remove that '}' on line 8.
Also the HTML element doesn't exists!
I think I know what's your problem. You need a while loop that loops al the "courses" and in that loop you execute a second query where you select the lessons where the course_id is equal to the current course id you're looping. A little dummy code for you.
<?php
while($row = mysql_fetch_assoc(mysql_query("SELECT * FROM courses"))) {
//display the course
while($row2 = mysql_fetch_assoc(mysql_query("SELECT * FROM lessons WHERE course_id=" . $row['id']))) {
//display the lessons of that course
}
}
?>

Categories