Display MySQL column value count only [duplicate] - php

This question already has answers here:
How to get count of rows in MySQL table using PHP?
(3 answers)
Closed 2 years ago.
How do I display this query result:
from MySQL onto a webpage, just like this:
?
I want to display the count only. I did run the same query through PHP but its returning '2'. The PHP code is below
<?php
//Connection for database
$conn = mysqli_connect("localhost", "root", "aaaaa", "db");
$query = "SELECT `gender`,COUNT(`gender`) FROM `reg` GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result)
{
// it return number of rows in the table.
$row = mysqli_num_rows($result);
if ($row)
{
printf("" . $row);
}
// close the result.
mysqli_free_result($result);
}
// Connection close
mysqli_close($conn);
?>
Please note that I have gone through other answers like this one but I can't really find my way through, I want the value count only not the total number of all rows in the table, .e.g. count for 'Male'.

You're using mysqli_num_rows(), which returns the number of rows in the result, not the actual data in the result. For that you need to use mysqli_fetch_assoc().
Your could would become:
$query = "SELECT `gender`,
COUNT(`gender`) AS `count`
FROM `reg`
GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$gender = $row['gender'];
$count = $row['count'];
echo "$gender = $count<br>";
}
mysqli_free_result($result);
}
Note that I slightly changed your query to make the count accessible.

Related

MySql SUM not returning any results [duplicate]

This question already has answers here:
Get sum of MySQL column in PHP
(9 answers)
Closed 1 year ago.
I'm trying to get the sum off all the prize money from a column in a MySql table, but I'm not getting a result.
$result = mysqli_query("SELECT SUM(prize_money) FROM cards");
while ($rows = mysqli_fetch_array($result)) {
echo $rows['SUM(prize_money)'];
}
I just want to add all of the numbers in the prize_money column then echo the results.
Thank You
You should apply an alias to the SUM so it is easier to access in the PHP.
You then need to pass the connection string to the mysqli_query function as the first parameter.
So for example if your database connection were:
$con=mysqli_connect("localhost","my_user","my_password","my_db");
then you'd use this code to execute the query and assign the alias:
$result = mysqli_query($con, 'SELECT SUM(prize_money) AS sum_prize_money FROM cards');
$row = mysqli_fetch_assoc($result);
$sum = $row['sum_prize_money'];
echo $sum;
Do you get a result if you do this:
$result = mysqli_query("SELECT SUM(prize_money) FROM cards");
$rows = mysqli_fetch_array($result);
echo $rows
As good practice, you should learn to aliase your sql variables e.g. SUM(prize_money) AS total etc

What's wrong with my query? Cannot fetch records [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My query isn't working. It does not print the record, but in phpmyadmin it does bring up a record.
$sql1 = "SELECT fullname FROM addresses WHERE userid = 1 LIMIT 1";
$result1 = mysqli_query($conn, $sql1);
while ($row = mysqli_fetch_row($result1)) {
$fullname = $row['fullname'];
$i++; }
echo $fullname;
UPDATE:
It was that my table did not have a unique key.
From the documentation:
Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero).
Your value is in $row[0], not $row['fullname'].
If you want an associative array, use mysqli_fetch_assoc or mysqli_fetch_array.
I believe mysql_fetch_assoc should be the way to go for this type of data retrieval, however, to give you an answer following your code, here it is.
$conn = mysqli_connect($host,$user,$password);
mysqli_select_db($conn, $database);
$i = 0;
$sql1 = "SELECT fullname FROM addresses WHERE userid=1 LIMIT 1";
$result1 = mysqli_query($conn, $sql1);
while ($row = mysqli_fetch_row($result1)) {
$fullname = $row[0];
$i++; }
echo $fullname;
You're getting the data using the index name
'fullname'
Like so,
$fullname = $row['fullname'];
But if you display the value of $row before the while loop, you can see that the option available is the actual numbered index only.
Also, you need to make sure that you're using mysqli_connect and mysqli_select_db when using mysqli_query and mysqli_fetch_row.
You didn't need while loop for set single records from database. Below i have updated your code for single record.
$query = "SELECT fullname FROM addresses WHERE userid = 1 LIMIT 1";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
echo "Full Name:". $row['fullname'];

Count function not counting all rows in db table

I am trying to count the number of rows in a table, using the count function. I currently have 5 rows in the table in question. However the count function is only counting 1 row. Why is this? Any suggestions.
$count_pcode = mysqli_query($dbc, "SELECT COUNT(*)FROM Delivery_Pcode");
$count_row =mysqli_num_rows($count_pcode);
printf("%d results.\n",$count_row);
mysqli_free_result($count_pcode );
mysqli_close($dbc);
Just change the first line to:
$count_pcode = mysqli_query($dbc, "SELECT * FROM Delivery_Pcode");
The next line of code will then tell you how many rows your query return
$count_row =mysqli_num_rows($count_pcode);
This code should count the number of rows, and do so efficiently.
$result = mysql_query($dbc, "SELECT COUNT(*)FROM Delivery_Pcode");
// Verify it worked
if (!$result) echo mysql_error();
$row = mysql_fetch_row($result);
// Should show you an integer result.
print_r($row);
mysqli_free_result($result);
mysqli_close($dbc);
Try the following:
$count_pcode = mysqli_query($dbc, "SELECT * FROM Delivery_Pcode");
$count_row = mysqli_num_rows($count_pcode);

Count number of rows in SQL database

I am trying to view how many rows there are based on a SQL query using PHP.
I seem to be able query the database and return fields from a row but can't seem to find out how many rows there are based on the same query.
<?php
$host = 'localhost';
$user = 'MyUsername';
$pass = 'MyPassword';
$database = 'MyDatabase';
$con=mysqli_connect($host,$user,$pass ,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
mysqli_close($con);
?>
All it returns is the text Rows on the screen, without the number of rows at the start.
Like I said, this same query works and returns a value if I try and select a row using:
while($row = mysqli_fetch_array($result))
{
echo $row["test"];
}
Anyone know why it won't return the number of rows?
You are using MySQLi. Because of you don't have a mysql query, mysql_num_rows doesn't return desired value.
You have to replace your mysql function with mysqli equal:
$num_rows = mysqli_num_rows($result);
You are using Mysqli to you should use mysqli_num_rows
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysqli_num_rows($result);
If you want only count then you can directly use count(*) like this:-
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result;
I'll do some thing like this:
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result

PHP - Select a unique mysql line without while [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
I want to select only unique values with php/mysql.
I can do it with many line, but I forget how to do it without while... :)
Thanks a lot.
Here is the code that I want to do without while.
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
while($row = mysql_fetch_array($result_1m))
{
/* Get the data from the query result */
$date1_1m = $row["date1"];
$date2_1m = $row["date2"];
}
mysql_fetch_assoc + SELECT with DISTINCT
I'm not sure I understand your question, but here's what I think you want to do :
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
list($date1_1m, $date2_1m) = mysql_fetch_row($result_1m);
Note that this will only get the first row from the result set (just as if you LIMIT 1)
like this?
$dbresult = mysql_query("SELECT DISTINCT field FROM table");
$result = array();
while ($row = mysql_fetch_assoc($dbresult))
{
$result[] = $row;
}
This gets you all unique values from "field" in table "table".
If you really wish to avoid the while loop, you can use the PHP PDO objects, and in particular call the PDO fetchAll() method to retrieve the complete results array in one go. PDO fetchAll() documentation
$db = new PDO('dblib:host=your_hostname;otherparams...');
$db->query("SELECT DISTINCT col FROM table");
$results = $db->fetchAll();
// All your result rows are now in $results
Heres how I do it and Json encode after. This will ensure it will encode only UNIQUE json Values (Without duplicates) as an example
$tbl_nm = "POS_P";
$prod_cat = "prod_cat";
//Select from the POS_P Table the Unique Product Categories using the DISTINCT syntax
$sql = "SELECT DISTINCT $prod_cat FROM $tbl_nm";
//Store the SQL query into the products variable below.
$products = mysql_query($sql);
if ($products){
// Create an array
$rows = array();
// Fetch and populate array
while($row = mysql_fetch_assoc($products)) {
$rows[]=$row;
}
// Convert array to json format
$json = json_encode(array('Categories'=>$rows));
echo $json;
}
//Close db connection when done
mysql_close($con);
?>
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
$date1_1m = $row["date1"];

Categories