PHP MySQL Display counts - php

I have this query for counting the number of items in a category:
SELECT category, COUNT(*) AS category_count FROM users GROUP BY category
Which creates results looking like:
category category_count
========== ================
X 3
Y 2
Now, In PHP I want to display the counts of the categories. For example, I might want to echo the count from category X, how would I do it?
Thanks in advance

Assuming $result holds the result of your query:
while ($row = mysql_fetch_array($result))
{
echo 'Category: ' . $row['category'];
if ($row['category'] == 'X')
{
echo ' Count: ' . $row['category_count'];
}
echo '<br/>';
}

$res = mysql_query("SELECT category, COUNT(*) AS category_count FROM users GROUP BY category");
while($row = mysql_fetch_assoc($res)){
echo $row['category'].": ".$row['category_count']."<br/>";
}

$result = mysql_query("SELECT category, COUNT(*) AS category_count FROM users GROUP BY category");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
{
if ( $row['category'] == 'x' )
{
echo $row['category_count'];
}
}

while ($row = mysql_fetch_array($result))
{
echo 'Category: ' . $row['category'] . ' Count:' . $row['category_count'];
echo "<br>";
}

It would be better if you use the where clause in your query.
SELECT COUNT(*) AS category_count FROM users WHERE category = 'x'

$conn = mysql_connect("address","login","pas s");
mysql_select_db("database", $conn);
$Var = mysql_query("query");
While ($row = mysql_fetch_assoc($var) { echo $var["column"] }.

Related

Separate records with comma

I'm new to php and I want to separate the records with a comma.
Database:
the table in sql
I use this code to get the data:
<?php
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result))
{
echo "Test: " . $row["value"]. "<br>";
}
mysqli_close($con);
?>
It return twice as:
Test: Test
Test: Test1
I want to separate the records with a ',' like this:
Test: Test, Test1
Store your values in an array and than implode with ",". You will get the result:
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
$yourArr = array();
while($row = mysqli_fetch_array($result))
{
$yourArr[] = $row["value"];
//echo "Test: " . $row["value"]. "<br>";
}
echo "Test: ". implode(",",$yourArr);
You can do this entirely in MySQL using GROUP_CONCAT:
<?php
$id = get_the_ID();
$sql = "SELECT `parent_id`, GROUP_CONCAT(`value` SEPARATOR ', ') AS comma_separated_values
FROM tablename
WHERE `parent_id` = '$id'
GROUP BY `parent_id`";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result))
{
echo 'Test: ' . $row["comma_separated_values"]; // Test: test, test2
}
mysqli_close($con);
?>
You should change the "comma_separated_values" name to something more appropriate for your data.
In your particular case, you would not need the while() loop either as we're limiting the MySQL to a single row.
If you were to remove the WHEREparent_id= '$id' from the SQL query, then you could return the results of multiple parent_id values. For example:
while ($row = mysqli_fetch_array($result))
{
echo 'Parent ' . $row['parent_id'] .': ' . $row["comma_separated_values"] . '<br>';
}
Would return:
Parent 292: Test1, Test2
Parent 293: Test3, Test4
Parent 294: Test5, Test10, Test50
etc...
you can use update query for this
$query="Update tablename set value=CONCAT(value,',test1') where parentid='295'";
$result=mysqli_query($conn,$query);

How can i make a table while fetch assoc

Hello i'm a (beginning) php backend dev and i'm working on a dj panel but it doesnt work the right way i tried as many things as i could but i cant get it to work..
$active_ids = '1, 3, 4';
$query = "SELECT * FROM users WHERE id IN ({$active_ids})";
$result = $mysqli->query($query);
$query2 = "SELECT dj, count(*) AS n FROM timetable WHERE dj IN ({$active_ids}) GROUP BY dj";
$result2 = $mysqli->query($query2);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo "<tr>";
echo "<td>", $row['username'] ,"</td>";
}
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()){
echo "<td>", $row2['n'] ,"</td>";
echo "</tr>";
}
}
}
this is what it shows
ZOMBOY
Hater
ZOMBOY2 3
1
1
and this is how it needs to become but i cant find a way to do it
ZOMBOY 3
Hater 1
ZOMBOY2 1
You can use join instead to querying two table
$active_ids = '1, 3, 4';
$query = "SELECT u.username, count(*) AS n FROM users u, timetable tt WHERE u.id=tt.dj and u.id IN ({$active_ids}) GROUP BY tt.dj";
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo "<tr>";
echo "<td>", $row['username'] ,"</td>";
echo "<td>", $row['n'] ,"</td>";
echo "</tr>";
}
}
You can do it like this, but must be look Joins
$active_ids = '1, 3, 4';
$query = "SELECT * FROM users WHERE id IN ({$active_ids})";
$result = $mysqli->query($query);
$query2 = "SELECT dj, count(*) AS n FROM timetable WHERE dj IN ({$active_ids}) GROUP BY dj";
$result2 = $mysqli->query($query2);
$columnOne = Array();
$columnTwo = Array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$columnOne[]= $row['username'];
}
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()){
$columnTwo[] = row2['n'];
}
}
}
echo '<table>';
for($i=0;$i<count($columnOne);$i++){
echo '<tr><td>' . $columnOne[$i] . '</td><td>' . $columnTwo[$i] . '</td></tr>';
}
echo '</table>';
You could try something such as this (Not quite as elegant as others):
# Escape your characters
$active_ids = "'1', '3', '4'";
# Tidy up the querys to reduce the change of reserved words being used
$query = "SELECT * FROM `users` WHERE `id` IN ({$active_ids});";
$result = $mysqli->query($query);
$query2 = "SELECT `dj`, COUNT(*) AS n FROM `timetable` WHERE `dj` IN ({$active_ids}) GROUP BY `dj`";
$result2 = $mysqli->query($query2);
# Count your results
$c1 = count($result);
$c2 = count($result2);
#Set the counter to be the larger of the 2
$counter = (($c1 > $c2) ? $c1 : $c2);
if ($result->num_rows > 0 && $result2->num_rows > 0)
{
# Print the table opener
print '<table class="your_class">';
# Loop through your results
for ($i = 0; $i < $counter; $i++)
{
# Print the data needed
print '<tr><td>' . $result[$i]['username'] . '</td><td>' . $result2[$i]['n'] . '</td></tr>';
}
# End the table
print '</table>';
}

PHP MySQL - foreach loop with if to display subset list within key list

I am trying to display records of venues, with a listing of rooms within each unique record. I have two tables, a venue_lookup table and a venue_lookup_room table. using the slow example I am struggling to ONLY populate each venue with the rooms that are contained within. I am able to echo the rooms into the venues, but I am struggling to restrict the rooms to ONLY appear with their unique parent venue. There is something simple that i am not seeing, I just know it.
//VENUE w VENUE ROOMS ARRAY TEST 2
$selCity = $_GET['theOption']; //Per Comment below modified $_POST to $_GET
$result5 = mysql_query("SELECT *
FROM lookup_venue_room INNER JOIN lookup_venue
ON lookup_venue_room.venue_name = lookup_venue.venue_name
WHERE lookup_venue.venue_city = '$selCity'
AND lookup_venue.venue_name = lookup_venue_room.venue_name") or die('ERROR' . mysql_error());
$roomNames = array();
$venueNames =array();
while($row2 = mysql_fetch_array($result5)) {
$roomNames[] = $row2['venue_room_name'];
$venueNames[] = $row2['venue_name'];
}
$result6 = mysql_query("SELECT * FROM lookup_venue WHERE lookup_venue.venue_city = '$selCity'")
or die('ERROR:' . mysql_error());
while($row = mysql_fetch_array($result6))
{
echo '<h3>' . $row['venue_name'];
echo '<select name="rooms">';
$venueNameOrig = $row['venue_name'];
foreach ($roomNames as $roomName) {
if ($row2['venue_name'] == $venueNameOrig ) {
echo '<option value="' . $roomName . '" selected="selected">' . $roomName . '</option>';
}
else {
echo '<option value="None">Non-venue-name-match</option>';
}
}
echo '</select>';
}

How to number each row returned from mysql as they are returned

So What I want to do is to echo 1 for the first row that is returned and two for the 2nd one and so one, Please I just don't know how to phrase this, I don't want to just count rows from mysql table, I want to give each row a number automatically and echo that number.
Please forgive my deprecated code.
$log = mysql_query("SELECT * FROM $table WHERE $columnid = '$id'") or die (mysql_error());
while($row = mysql_fetch_array($log)){
echo row['name'];
}
Lets assume that the above returns some names. so I want this.
1 : John
2 : Nancy
3 : Dave
I don't want to write those number.
Please take into account ORDER by rate DESC since I'm using that to descent the number by the biggest number of rate.
You could do:
$count = 1;
while($row = mysql_fetch_array($log)){
echo $count . ' ' . row['name'];
$count++;
}
Or:
echo '<ol>';
while($row = mysql_fetch_array($log)){
echo '<li>' . row['name'] . '</li>';
}
echo '</ol>';
$log = mysql_query("SELECT * FROM $table WHERE $columnid = '$id'") or die (mysql_error());
$c = 0
while($row = mysql_fetch_array($log)){
echo row['name'];
$c = $c + 1;
}
echo "Raw Count = ".$c

Output distinct values in SQL column with 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

Categories